2017-12-02 147 views
0

我有問題要結合兩個陣列,在這裏我的示例代碼笨結合在foreach循環×2個陣列

$arr1 = []; 
$data = $this->db->query("SELECT QUERY"); 

foreach ($data->result_array() as $row) { 

$arr1[] = array(
    "type"     => "column", 
    "name"     => $row['name'], 
    "legendText"    => $row['name'], 
    "showInLegend"   => true 
); 

} 


$count = $this->db->query("SELECT QUERY"); 

foreach ($count->result_array() as $rows) { 

$arr1[]["dataPoints"] = array(
    "label" => $rows['data'] 
); 

} 

有了這個代碼,結果是

[ 
    { 
    "type": "column", 
    "name": "LA 1", 
    "legendText": "LA 1", 
    "showInLegend": true 
    }, 
    { 
    "dataPoints": { 
     "label": "1" 
    } 
    } 
] 

我想合併兩個數組,所以輸出應該是這樣的:

[ 
    { 
    "type": "column", 
    "name": "LA 1", 
    "legendText": "LA 1", 
    "showInLegend": true, 
    "dataPoints": [{ 
     "label": "1" 
    }] 
    } 
] 

請有人幫我找出最簡單的方法來解決這個問題。

+0

http://php.net/manual/en/function.array-merge.php –

+0

不是多維數組的最佳選擇 – Alex

回答

2

解決此問題的正確方法是將數據庫查詢更改爲將返回單個查詢中的所有信息的查詢。

$data = $this->db->query("SELECT a.*, b.datapoints FROM table1 a, table2 b....");