PHP中兩個數組合并可以使用+或者array_merge,但之間還是有區別的,本篇文章介紹的就是PHP數組合并+與array_merge的區別分析和對多個數組合并去重技巧 ,有需要的朋友可以看一下本文。
主要區別是兩個或者多個數組中如果出現相同鍵名,鍵名分為字串或者數字,需要注意
1)鍵名為數字時,array_merge()後面的值將不會覆蓋原來的值,而是附加到後面,但+合并數組則會把最先出現的值作為最終結果返回,而把後面的數組擁有相同鍵名的那些值“拋棄”掉(不是覆蓋)
2)鍵名為字串時,array_merge()此時會覆蓋掉前面相同鍵名的值,但+仍然把最先出現的值作為最終結果返回,而把後面的數組擁有相同鍵名的那些值“拋棄”掉(不是覆蓋)。
需要注意的是數組鍵形式 '數字' 等價於 數字
$a = array('a', 'b');$b = array('c', 'd');$c = $a + $b;var_dump($a);var_dump(array_merge($a, $b));//輸出:array 0 => string 'a' (length=1) 1 => string 'b' (length=1)array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'd' (length=1)++++++++++++++++++++++++++++++++++++++++++ $a = array(0 => 'a',1 => 'b');$b = array(0 => 'c',1 => 'b');$c = $a + $b;var_dump($c);var_dump(array_merge($a, $b));//輸出:array 0 => string 'a' (length=1) 1 => string 'b' (length=1)array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1)++++++++++++++++++++++++++++++++++++++++++ $a = array('a', 'b');$b = array('0' => 'c',1 => 'b');$c = $a + $b;var_dump($c);var_dump(array_merge($a, $b));//輸出:array 0 => string 'a' (length=1) 1 => string 'b' (length=1)array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1)++++++++++++++++++++++++++++++++++++++++++ $a = array(0 => 'a',1 => 'b');$b = array('0' => 'c','1' => 'b');$c = $a + $b;var_dump($c);var_dump(array_merge($a, $b));輸出:array 0 => string 'a' (length=1) 1 => string 'b' (length=1)array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1)
對多個數組合并去重技巧
$a = array('1001','1002');$b = array('1002','1003','1004');$c = array('1003','1004','1005');$d = count(array_flip($a) + array_flip($b) + array_flip($c));