php ActiveRecord + CodeIgniter - 从查询中返回单个值,而不是数组形式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2672163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ActiveRecord + CodeIgniter - Return single value from query, not in array form
提问by txmail
Say you construct an activerecord query that will always just return a single value, how do you just address that single value instead of getting an array in return? For instance I am using an ActiveRecord query to return the SUM of a single column, it will only return this one single SUM, instead of having to parse the array is there a way to assign the value as a function return equal to that value instead of getting an array?
假设您构建了一个始终只返回单个值的 activerecord 查询,您如何只处理该单个值而不是获取数组作为回报?例如,我使用 ActiveRecord 查询来返回单个列的 SUM,它只会返回这个单个 SUM,而不必解析数组是否有一种方法可以将值分配为等于该值的函数返回值获取数组?
回答by Bj?rn B?rresen
$query = $this->db->get(); // your ActiveRecord query that will return a col called 'sum'
echo $query->row('sum');
回答by Yogesh Malpani
$output = $this->db->query("YOUR QUERY")->row()->fieldname;
OR
或者
$output = $this->db->get("TABLE NAME")->row()->fieldname;
Where fieldnameis the name of the field you want the output of in your query.
fieldname您希望在查询中输出的字段的名称在哪里。
回答by Galen
this isn't the prettiest way. i can't find a way to do it with the active record api. but here's a one-liner to get it.
这不是最漂亮的方式。我找不到使用活动记录 api 的方法。但这里有一个单线来获得它。
$result = array(
array('sum' => '23')
);
echo current( current( $result ) );

