简体   繁体   English

通过数字索引获取ASSOC数组值

[英]Get ASSOC array value by numeric index

In all the examples of Codeigniter queries at https://www.codeigniter.com/user_guide/database/results.html , I find that the name of the field must be known to get its value. https://www.codeigniter.com/user_guide/database/results.html上的所有Codeigniter查询示例中,我发现必须知道该字段的名称才能获得其值。

$query = $this->db->query("SELECT title,name,body FROM table");

foreach ($query->result() as $row)
{
  echo $row->title;
  echo $row->name;
  echo $row->body;
}

For example, if I want to get the title , I will perform row->title . 例如,如果我想获得title ,我将执行row->title Is there a way to get the title using an index eg like $row[0] ? 有没有办法使用索引获取title ,例如$row[0]

Use result_array function returns the query result as a pure array 使用result_array函数将查询结果作为纯数组返回

$query = $this->db->query("SELECT title,name,body FROM table");
    $result = $query->result_array();
    foreach($result as $res){
      echo $res['title'];
      echo $res['name'];
      echo $res['body'];
    }

if you want to access via index then use array_values: 如果要通过索引访问,则使用array_values:

    $result = $query->result_array();
    foreach($result as $res){
      $r = array_values($res);
      echo $r[0];
      echo $r[1];
      echo $r[2];
    }
<?php
  $result = $subject_code->result_array();
   foreach($result as $res){
   $r = array_values($res);
   print_r($r);
   }
?>
I applied the above code but in o/p index of each value is comming 0
o/p- Array ( [0] => 201 ) Array ( [0] => 202 ) Array ( [0] => 203 ) Array ( [0] => 204 ) Array ( [0] => 205 ) 

Slightly more elegant way: 稍微优雅的方式:

$data = $this->db->query("SELECT title,name,body FROM table")->result_array();

array_walk($data,function(&$row) {
    $row = array_values($row);
});

And you have $data array with numeric indexes. 你有$ data数组和数字索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM