【问题标题】:Get ASSOC array value by numeric index通过数字索引获取 ASSOC 数组值
【发布时间】:2014-02-18 13:06:49
【问题描述】:

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;
}

例如,如果我想获得title,我将执行row->title。有没有办法使用索引来获取title,例如喜欢$row[0]

【问题讨论】:

  • 它是对象,你不能将对象用作数组。

标签: php arrays database codeigniter associative-array


【解决方案1】:

使用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'];
    }

如果您想通过索引访问,请使用 array_values:

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

【讨论】:

  • -1 OP 希望通过数字索引而不是键名获取值。
【解决方案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】:

    稍微优雅一点的方式:

    $data = $this->db->query("SELECT title,name,body FROM table")->result_array();
    
    array_walk($data,function(&$row) {
        $row = array_values($row);
    });
    

    你有带有数字索引的 $data 数组。

    【讨论】:

      猜你喜欢
      • 2017-12-04
      • 2011-04-10
      • 1970-01-01
      • 2017-08-27
      • 2021-07-12
      • 2022-07-25
      • 1970-01-01
      • 2011-09-17
      • 2013-10-07
      相关资源
      最近更新 更多