2011-08-11 57 views
4

說我有:如何在php中組合數組,以便第二個數組覆蓋第一個數組?

$arr1 = array('green', 'yellow', 'blue', 'red'); 
$arr2 = array('yellow', black, white, 'red'); 

如果我這樣做array_merge($arr1, $arr2,)這給:

array(green, yellow, blue, red, yellow, black, white, red); 

我希望確保在數組中沒有重複,注意,我沒有使用數組鍵,只值。

有沒有另一個簡單的解決方案,我失蹤了?

回答

4
array_unique(array_merge($arr1, $arr2)); 
2

沒有爲一個功能上PHP.net:
http://php.net/manual/en/function.array-unique.php

$unique_array = array_unique(array_merge($array1, $array2, ....)); 

而且從文檔請注意,如果你要使用的密鑰
"Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys"

專業提示:可怕的命名,你應該使用比我更好的名字

1

只需使用array_unique刪除所有非唯一值:

$merged = array_unique(array_merge($arr1, $arr2)); 
相關問題