2017-08-01 175 views
0

我想加入兩個數組,其中1個鍵應該加入它們。PHP合併數組並保留鍵

array:1 [ 
     0 => array:2 [ 
     "MONAT" => "AUG" 
     "MAIL_CNT" => "2" 
     ] 
    1 => array:2 [ 
     "MONAT" => "JUL" 
     "MAIL_CNT" => "1" 
     ] 
    ] 

    array:2 [ 
     0 => array:2 [ 
     "MONAT" => "AUG" 
     "ORDER_CNT" => "18" 
     ] 
     1 => array:2 [ 
     "MONAT" => "JUL" 
     "ORDER_CNT" => "1" 
     ] 
    ] 

結果應該是這樣的

array:1 [ 
     0 => array:2 [ 
     "MONAT" => "AUG" 
     "MAIL_CNT" => "2" 
     "ORDER_CNT" => "18" 
     ] 
    1 => array:2 [ 
     "MONAT" => "JUL" 
     "MAIL_CNT" => "1" 
     "ORDER_CNT" => "1" 
     ] 
    ] 

我無法弄清楚該怎麼做。

在此先感謝和問候!

+5

可能重複的[PHP:合併兩個數組,同時保留鍵而不是重新索引?](https://stackoverflow.com/questions/3292044/php-merge-two-arrays-while-keeping-keys-instead-of -reindexing) – Difster

+0

您的關鍵MONAT應該與兩者匹配嗎?該條件? – Alice

回答

1

使用array_replace_recursive

$array = array_replace_recursive($a1, $a2); 
+1

令人信服,但如果條件是月份必須匹配和陣列長度不匹配這兩個陣列,那麼它將失敗 – Alice

+0

工程就像一個魅力!我感到有點慚愧,我只是嘗試array_replace :-) – WhiteRabbit

0
$mergedArray = array(); 
foreach($arr1 as $key => $row) { 
    $mergedArray[$key] = array_merge($arr2[$key], $row) 
} 

希望這有助於

+0

雖然這種方法沒有太多可移動的部分來討論,但重要的是嘗試提供一些答案和答案,並避免僅用於代碼的帖子,以便將來的SO讀者受到教育。 – mickmackusa

1

你應該使用PHP array_replace_recursive()這個

$arr1=array(
    0 =>array(
     "MONAT" => "AUG", 
     "MAIL_CNT" => "2" 
    ), 
    1 => array(
     "MONAT" => "JUL", 
     "MAIL_CNT" => "1" 
    ) 
); 

$arr2=array(
    0 => array(
     "MONAT" => "AUG", 
     "ORDER_CNT" => "18" 
    ), 
    1 => array(
     "MONAT" => "JUL", 
     "ORDER_CNT" => "1" 
    ) 
); 

$array = array_replace_recursive($arr1, $arr2); 
echo"<pre>"; print_r($array); 
+0

@ jiboulex已經回答說.... – Alice

0

1:簡單的使用array_merge

第二:&意味着它是按引用傳遞的value

foreach($array1 as $key => &$val) { 
    $val = array_merge($val,$array2[$key]); 
} 
print_r($array1); 

注代替:如果both array count是同一否則會拋出錯誤上面的代碼將只工作。