我是CodeIgniter的新手。我喜欢它,它很棒,但一个问题几天都解决不了。
我正在尝试通过其 id 获取一行,如下所示:
$query = $this->db->get_where('content', ['id' => $id]);
$the_content = $query->result_array();
但是,它会产生大小为 1 的数组,如下所示:
$the_content = [ 0 => ['id' => 1, 'content'=> 'abc']];
所以我总是必须像这样将其转换为它的第一个元素:
$the_content= $the_content[0];
但你可以理解为什么我不喜欢这样。
我也试过$query->result();
,还是一样。
确定我在这里错过了一个简单的点,但是呢?
如何从活动记录而不是数组中获取单个元素?
解决方案是:
$the_content = $query->row_array();
返回单个维度数组。要检索,请编写:
echo $the_content['content'];
使用 first_row()
:
$row = $query->first_row();
如果你想要一个数组:
$row = $query->first_row('array')
或者,如果您希望返回特定行,则可以在第一个参数中将行号作为数字提交:
$row = $query->row_array(3);
如果要获取第一行的字段:
$field = $query->first_row()->field;
echo $field;
请参阅此处的文档。
有一个函数可以从查询中获取第一行:
$the_content = $query->first_row('array')
参考: http://ellislab.com/codeigniter/user-guide/database/results.html