Get ASSOC array value by numeric index

人走茶凉 提交于 2020-01-06 04:05:38

问题


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.

$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. Is there a way to get the title using an index e.g. like $row[0]?


回答1:


Use result_array function returns the query result as a pure 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:

    $result = $query->result_array();
    foreach($result as $res){
      $r = array_values($res);
      echo $r[0];
      echo $r[1];
      echo $r[2];
    }



回答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 ) 



回答3:


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.



来源:https://stackoverflow.com/questions/21854774/get-assoc-array-value-by-numeric-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!