问题
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();
I tried using $query = array_merge($results1, $results2);
but that does not work, I believe because ->get()
is returning an array of objects.
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.
回答1:
You can use like below
$arr_results1 = $this->db->get()->result_array();
$arr_results2 = $this->db->get()->result_array();
var_dump(array_merge($arr_results1,$arr_results2));
Hope this will help you!
回答2:
After a bit of reading I came up with the following and it works!
//first query here...
$results1 = $this->db->get()->result_array();
//second query here...
$results1 = $this->db->get()->result_array();
//then...
$query = array_merge($results1,$results2);
回答3:
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.
For example
# ...
$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...
}
来源:https://stackoverflow.com/questions/32535014/php-codeigniter-merging-query-results-before-foreach-loop