php 在 Codeigniter 中使用 $this->db->get()->row_array()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9760256/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:34:47  来源:igfitidea点击:

Using $this->db->get()->row_array() in Codeigniter

phpcodeigniter

提问by Nyxynyx

I'm using $this->db->get()->row_array()in Codeigniter to get a single row of results from the database. I want to merge the results from all the different queries into a single array $results; So I dont want to have to type in the column name to get the result of a single row...

$this->db->get()->row_array()在 Codeigniter 中使用从数据库中获取单行结果。我想将所有不同查询的结果合并到一个数组中$results;所以我不想输入列名来获得单行的结果......

PHP Code

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'];

These 2 lines below appear to me that there can be a shorter way to write this. Is there? THanks!

下面的这两行在我看来可以用更短的方式来写。在那儿?谢谢!

$result = $this->db->get()->row_array();
$results['num'] = $result['num'];

Desired solution

所需的解决方案

$results['num'] = first_element_of($this->db->get()->row_array());will be great!

$results['num'] = first_element_of($this->db->get()->row_array());会很棒!

回答by Basti

Don't know codeigniter and have never worked with it but this might work

不知道 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;

The trick is that you can chain object member access. You cannot do this with arrays ($foo->row_array()['num']), so that's the problem here. If you were using good old mysql you should have a look at mysql_result. There is no mysqli equivalent for this.

诀窍是您可以链接对象成员访问。你不能用数组 ( $foo->row_array()['num'])做到这一点,所以这就是问题所在。如果您使用的是旧的 mysql,您应该查看mysql_result。没有与此等效的 mysqli。

Depending on the return value of where() you can try and shorten it further to

根据 where() 的返回值,您可以尝试将其进一步缩短为

$results = array('num' => 
    $this->db->select('COUNT(listing_id) as num')
        ->from('listings')
        ->where('city', $city)
        ->get()
        ->row()
        ->num
);