2017-08-09 101 views
2

我有兩個數組,即arr和arr2。具有公共值的合併陣列

var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]; 

var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}]; 

是否有可能從上面的數組中獲得數組?

result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]; 

如果我使用array_merge然後我得到的答案

result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}]; 
+1

發生這種情況是因爲如果鍵是數字,'array_merge'不會合並,而是追加新的數據。從PHP手冊:*如果輸入數組具有相同的字符串鍵,則該鍵的後面的值將覆蓋前一個。但是,如果數組中包含數字鍵,則後面的值不會覆蓋原始值,但會被追加。* – tilz0R

+0

ok先生。有沒有可能獲得預期的答案? – Raj

+0

在使用array_merge或更好的array_merge_recursive合併在一起之前,請確保您的數組包含非數字鍵。例如,您可以將月份名稱設置爲月份數據的關鍵字。 – tilz0R

回答

1

想到的第一個函數是array_merge_recursive(),但即使將臨時關聯密鑰分配給子陣列,也會在多個深度子陣列中產生多個January值。

但是不要絕望,還有另一個可以完成這項工作的遞歸函數。只要首先分配臨時關聯密鑰,array_replace_recursive()將成功合併這些多維數組。

這裏是一個單行不使用foreach()循環或if語句:

代碼:(Demo

$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true); 
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true); 
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month')))); 

輸出:

[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}] 

細目:

echo json_encode( // convert back to json 
     array_values( // remove the temp keys (reindex) 
      array_replace_recursive( // effectively merge/replace elements associatively 
       array_column($arr,NULL,'month'), // use month as temp keys for each subarray 
       array_column($arr2,NULL,'month') // use month as temp keys for each subarray 
      ) 
     ) 
    ); 
+0

是的......你的解決方案在這種情況下更好:) – Neodan

0

你應該寫自己的函數來做到這一點

$res = []; 
foreach ($arr as $item) { 
    $res[$item['month']] = $item; 
} 

foreach ($arr2 as $item) { 
    $res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item; 
} 

var_dump($res); 
2

您必須解碼JSON到數組,手動合併它們,再次編碼爲JSON :)

<?php 
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true); 
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true); 

$result = []; 
foreach ($arr as &$item) { 
    if (empty($arr2)) 
     break; 

    foreach ($arr2 as $key => $item2) { 
     if ($item['month'] === $item2['month']) { 
      $item = array_merge($item, $item2); 
      unset($arr2[$key]); 
      continue; 
     } 
    } 
} 
if (!empty($arr2)) 
    $arr = array_merge($arr, $arr2); 

echo json_encode($arr);