[英]Get associative array of each row in CodeIgniter ActiveRecord result
In CodeIgniter there is a function query->row_array
which will give you an associative array of your result, mapping column names to values.在 CodeIgniter 中有一个函数query->row_array
,它会给你一个结果的关联数组,将列名映射到值。 However this function only works if there is a single row as a result.但是,此功能仅在结果为单行时才有效。
What I need is a function which will return an associative array for each row in the query result.我需要的是一个函数,它将为查询结果中的每一行返回一个关联数组。
I am currently doing:我目前正在做:
$arr = array ();
foreach ($query->result() as $row) {
array_push ($arr, array("col1" => $row->col1, "col2" => $row->col2, ...));
}
return $arr;
Not only is this annoying to read and write, but it also doesn't scale as I add more columns to this table.这不仅读和写很烦人,而且当我向这个表添加更多列时它也不会扩展。 I have similar code in several places, and I wish I could replace it with something that is cleaner.我在几个地方有类似的代码,我希望我可以用更干净的东西替换它。
I was hoping for something like:我希望是这样的:
$arr = array ();
foreach ($query->result() as $row) {
array_push ($arr, $row->to_array());
}
return $arr;
Is there something like that?有这样的事情吗? Or even better:或者甚至更好:
return $query->result_array ();
Try试试
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
https://www.codeigniter.com/user_guide/database/results.htmlhttps://www.codeigniter.com/user_guide/database/results.html
Use this method,用这个方法,
$query = $this->db->get_where('table', array('table_id' => $id));
$queryArr = $query->result();
foreach ($queryArr[0] as $key=>$val)
{
$row[$key]=$val;
}
print_r($row); //$row will give associative array
you can use result_array()
see the original documentation http://ellislab.com/codeigniter/user-guide/database/results.html您可以使用result_array()
查看原始文档http://ellislab.com/codeigniter/user-guide/database/results.html
Sample code.示例代码。
$query = $this->db->query("YOUR QUERY");foreach ($query->result_array() as $row){ echo $row['title']; echo $row['name']; echo $row['body'];}
$this->db->row(); $this->db->row();
or或
$query->row(); $query->row();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.