[英]How to get the first data from an array
我在codeigniter的视图文件中有以下代码。
<?php foreach ($records as $rows){?>
<? echo $rows['product_name']; ?> <br>
<? } ?>
我的模特
$this->db->select('*');
$this->db->from('products');
$this->db->order_by('product_name','ASC');
$getData = $this->db->get('');
if($getData->num_rows() > 0)
return $getData->result_array();
else
return null;
如果运行上面的代码,我将得到以下结果
Pepsi
Coke
Mountain Dew
我试图仅显示第一个结果(百事可乐)。 您能告诉我该怎么做吗?
$ records是一个数组。 您可以像这样指定索引
<?=$records[0]['product_name']?>
使用LIMIT
告诉DB仅从数据库中提取有限数量的记录
$this->db->from('products LIMIT 0,1');
这应该工作:
$query = $this->db->limit(0, 1);
参见文档: http : //codeigniter.com/user_guide/database/active_record.html
另请参阅: CodeIgniter数据库查询限制
重置是解决此问题的另一种方法。 http://www.php.net/manual/zh/function.reset.php
因此在示例中,$ first_element = reset($ records);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.