2015-08-14 75 views
0

我一直在試圖合併這個數組,其中$array[4]存在多次,例如:$array[4] == 'red'恰好兩次。我怎樣才能合併這些數組,同時保持其他數據?我已經做了幾次嘗試,如果要求,我願意包括我的努力。在多維數組中複製的合併數組

考慮這個數組:

array(3) { 
    [0]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "532" 
       [2]=> 
       string(1) "2" 
       [3]=> 
       string(9) "Domain(s)" 
       [4]=> 
       string(20) "red" 
      } 
[1]=> 
    array(5) { 
      [0]=> 
       string(3) "UID" 
      [1]=> 
       string(3) "532" 
      [2]=> 
       string(7) "License" 
      [3]=> 
       string(3) "Fee" 
      [4]=> 
       string(20) "red" 
      } 
[2]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "536" 
       [2]=> 
       string(7) "License" 
       [3]=> 
       string(3) "Fee" 
       [4]=> 
       string(16) " University Test" 
      } 
    } 

努力實現:

array(3) { 
    [0]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "532" 
       [2]=> 
       string(1) "2" 
       [3]=> 
       string(9) "Domain(s)" 
       [4]=> 
       string(20) " red" 
       [5]=> 
       string(3) "Fee" 
       [6]=> 
       string(7) "License" 
      } 
[1]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "536" 
       [2]=> 
       string(7) "License" 
       [3]=> 
       string(3) "Fee" 
       [4]=> 
       string(16) " University Test" 
      } 
    } 
+0

是否有你已經嘗試任何方法? –

+0

你會得到重複的'key',然後使用'key'移除它。你會在'key'中留下空隙,但是你可以使用'array_values'來重新組織鍵。 – Script47

+0

結果數組中元素的順序是否重要? –

回答

1
foreach ($test as $item) { 
    if (!isset($merged[$item[4]])) { 
     // add the item to the merged array using key=$item[4] 
     $merged[$item[4]] = $item; 
    } else { 
     // merge the item with the item that is already in the array at key=$item[4] 
     $merged[$item[4]] = array_unique(array_merge($merged[$item[4]], $item)); 
     // array_unique is necessary because array_merge will not overwrite numeric keys 
    } 
} 
// convert the keys back to numeric (if you care to) 
$merged = array_values($merged); 
+0

這個。工作。謝了哥們。不知道你可以'array_unique(array_merge))'! – Kisaragi