2016-04-06 51 views
0

我有兩個PHP數組像下面,兩個數組合並或推動JSON

$health_table1[] = array(
      'department_name' => $department['department_name'], 
      'department_total' => $department_total); 


$health_table2[] = array(
      'status_name' => $status['status_name'], 
      'status_total' => $status_total); 

我想以這樣的方式來合併這兩陣列,它應該輸出JSON如下,

0 
: 
{department_name: "Iphone", department_total: 1, status_name: 'test1', status_total: 5} 
1 
: 
{department_name: "Macbook", department_total: 2, status_name: 'test2', status_total: 7} 
2 
: 
{department_name: "Training", department_total: 0, status_name: 'test3', status_total: 9} 

我試圖與array_merge,array_push但沒有幫助,

任何幫助表示讚賞,

由於

回答

1

我假設數組具有相同的長度。

我不知道你是怎麼嘗試,但你可以做array_merge這樣

$return = []; 
foreach($health_table1 as $key => $value){ 
    $return[] = array_merge($health_table1[$key], $health_table2[$key]); 
} 

echo json_encode($return);//<- here is the merged array. 
+0

@Dainel,是它的工作,在第一陣列中添加其他數組的鍵值,但如果第2個數組有什麼不同長度? – rjcode

+0

@rjcode這取決於你想要做什麼。如果您希望只有一個數組的值較短,或者只有兩個數組都有值的值。你將不得不適應一些ifs來檢查更長的陣列。 –