result_array返回值但在codeigniter中不返回$ key,如果我在视图中手动添加数据数组,它确实返回$ key,为什么它不回显$ key。
型号::
<?php
class Admin_user extends CI_Model
{
public function list_rows()
{
$query = array();
$query = $this->db->get('content');
return $query->result_array();
}
}
查看::
<?php
foreach ($get_all_content as $key => $values)
{
$title = $values['title'];
echo "<th>" . $key . "</th>";
}
?>
Controller ::
$data['get_all_content'] = $this->admin_user->list_rows();
Print_r ::
Array
(
[0] => Array
(
[id] => 1
[menu_id] => 12
[title] => Register Domain name for free
[sub_title] => This is the sub_title
[content] => this is the content description
[description] =>
[section] =>
)
)
答案 0 :(得分:0)
这是一个老问题,但是我现在在回答新用户的问题。
简短的答案是,当您使用result_array
检索数据库查询的结果时,将获得一个数组数组。每行都是它自己的数组,该行的键不是ID列。它只是一个从零开始的序号。
例如,如果我有一个这样的表:
+----+-----------+------------+
| id | username | updated |
+----+-----------+------------+
| 16 | nhageman | 2019-10-29 |
| 20 | hnoland | 2014-02-10 |
| 31 | lpostel | 2020-04-08 |
| 36 | lemmerich | 2016-03-08 |
| 77 | rhegwood | 2017-02-20 |
+----+-----------+------------+
...并运行Active Record查询,如下所示:
$results = $this->db
->get('users')
->result_array();
$results
数组将如下所示:
array (size=10)
0 =>
array (size=3)
'id' => string '16' (length=2)
'username' => string 'nhageman' (length=8)
'updated' => string '2019-10-29' (length=19)
1 =>
array (size=3)
'id' => string '20' (length=2)
'username' => string 'hnoland' (length=7)
'updated' => string '2014-02-10' (length=19)
2 =>
array (size=3)
'id' => string '31' (length=2)
'username' => string 'lpostel' (length=7)
'updated' => string '2020-04-08' (length=19)
3 =>
array (size=3)
'id' => string '36' (length=2)
'username' => string 'lemmerich' (length=9)
'updated' => string '2016-03-08' (length=19)
4 =>
array (size=3)
'id' => string '77' (length=2)
'username' => string 'rhegwood' (length=8)
'updated' => string '2017-02-20' (length=19)
重点是:
请注意,每行的数组键是0到4,而不是行ID。
因此,当您遍历数组时不能像预期的那样得到期望的结果:
// how to do it wrong
foreach ($results as $key => $row) {
echo $key . ':';
echo $row['username'] . '<br>';
}
错误的结果:
0: nhageman
1: hnoland
2: lpostel
3: lemmerich
4: rhegwood
您会看到$key
只是分配给每一行的自动顺序键。在大多数情况下,处理Active Record结果时,您可以忽略键,因为您要查找的行ID包含在$row
数组中:
// how to do it right
foreach ($results as $row) {
echo $row['id'] . ':';
echo $row['username'] . '<br>';
}
正确的结果:
16: nhageman
20: hnoland
31: lpostel
36: lemmerich
77: rhegwood
希望这可以为您澄清一下。