问题描述
我想知道如果可能合并sql查询像下面从codeigniters活动记录。
I would like know if it is possible to merge sql queries like the following from codeigniters active record.
//get assigned contacts
$this->db->select('*, CONCAT(first_name, " " ,last_name) AS name', FALSE);
$this->db->from('customers_contacts');
$this->db->join('customers_accounts', 'customers_accounts.contact_id = customers_contacts.contact_id');
$this->db->like('CONCAT(first_name, " " ,last_name)', $q);
$results1 = $this->db->get();
//get non assigned contacts
$this->db->select('*, CONCAT(first_name, " " ,last_name) AS name', FALSE);
$this->db->from('customers_contacts');
$this->db->like('CONCAT(first_name, " " ,last_name)', $q);
$results2 = $this->db->get();
我尝试使用 $ query = array_merge($ results1,$ results2);
但是不行,我相信因为 - > get()
返回一个对象数组。
I tried using $query = array_merge($results1, $results2);
but that does not work, I believe because ->get()
is returning an array of objects.
所以我让它通过一个foreach循环,然后合并结果数组工作。但我需要做一些条件,在一个foreach循环比两个更容易。
So I got it to work by putting both through a foreach loop, and then merging the resulting arrays. But I need to do some conditionals that would be easier in one foreach loop than two.
推荐答案
$ c> $ results-> result(); 在 $ results = $ this-> db-> get() code>。 注意:
$ results-> result();
是一个对象数组。
You must always do $results->result();
to get an array of rows after $results = $this->db->get();
. note: $results->result();
is an array of objects.
例如
# ...
$results1 = $this->db->get();
# ...
$results2 = $this->db->get();
$results = array();
if ($results1->num_rows())
{
$results = array_merge($results, $results1->result());
}
if ($results2->num_rows())
{
$results = array_merge($results, $results2->result());
}
return $results;
这将返回一个对象(行)数组,并像往常一样遍历数据:
This will return an array of objects (rows) and you iterate through data as usual:
foreach ($results as $row)
{
echo $row->id;
echo $row->column_name_1;
# and so on...
}
这篇关于PhP(Codeigniter)在foreach循环之前合并查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!