我在Codeigniter中使用$this->db->get()->row_array()
从数据库中获取单行结果。我想将来自所有不同查询的结果合并到一个数组$results
;所以我不想输入列名来获得单行的结果......
PHP代码
// Query 1
$results = array();
$this->db->select('COUNT(listing_id) as num')
->from('listings')
->where('city', $city);
$result = $this->db->get()->row_array();
$results['num'] = $result['num'];
下面这两行显示可以用更短的方式来写这个。在那儿?谢谢!
$result = $this->db->get()->row_array();
$results['num'] = $result['num'];
所需解决方案
$results['num'] = first_element_of($this->db->get()->row_array());
会很棒!
答案 0 :(得分:3)
不知道codeigniter并且从未使用过它,但这可能有效
// Query 1
$results = array();
$this->db->select('COUNT(listing_id) as num')
->from('listings')
->where('city', $city);
$results['num'] = $this->db->get()->row()->num;
诀窍是你可以链接对象成员访问。您无法使用数组($foo->row_array()['num']
)执行此操作,因此这就是问题所在。如果你使用的是旧的mysql,你应该看看mysql_result。这没有mysqli等价物。
根据where()的返回值,您可以尝试将其进一步缩短为
$results = array('num' =>
$this->db->select('COUNT(listing_id) as num')
->from('listings')
->where('city', $city)
->get()
->row()
->num
);