2015-09-12 56 views
0

我想知道是否有可能從codeigniters活動記錄中合併如下所示的sql查詢。PhP(Codeigniter)在foreach循環之前合併查詢結果

//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()將返回對象的數組。

因此,我通過將兩者都通過foreach循環,然後合併結果數組來實現它。但是我需要做一些在一個foreach循環中比兩個循環更容易的條件。

+0

對不起,我本來應該更清楚,因爲這兩個查詢都在同一個表中,只有一個與聯結表連接(已分配與未分配的聯繫人),分配的聯繫人中會返回額外的列。所以工會不行。 – skribe

+0

我認爲你需要這個:http://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array –

回答

0

經過一番閱讀後,我想出了以下,它的工作原理!

//first query here... 
$results1 = $this->db->get()->result_array(); 
//second query here... 
$results1 = $this->db->get()->result_array(); 
//then... 
$query = array_merge($results1,$results2); 
0

您可以使用如下

$arr_results1 = $this->db->get()->result_array(); 
$arr_results2 = $this->db->get()->result_array(); 
var_dump(array_merge($arr_results1,$arr_results2)); 

希望這將幫助你!

0

您必須始終執行$results->result();才能在$results = $this->db->get();之後得到一個行數組。 說明:$results->result();是一組對象。

例如

# ... 
$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; 

這將返回的對象(行)的數組,你通過數據像往常一樣重複:

foreach ($results as $row) 
{ 
    echo $row->id; 
    echo $row->column_name_1; 
    # and so on... 
}