我們現(xiàn)在來(lái)分析一下在PHP開發(fā)過程中,如何合并兩個(gè)數(shù)組,并且將相同鍵值的元素合并在一起。
示例1
最簡(jiǎn)單的合并方式
$a = [ 1=>'a', 2=>'b', 3=>'c' ]; $b = [ 3=>'e', 4=>'f', 5=>'c' ]; $c = $a+$b; print_r($c);
輸出:
Array ( [1] => a [2] => b [3] => c [4] => f [5] => c )
分析:$a[3]
覆蓋了$b[3]
,當(dāng)數(shù)組存在相同鍵值的元素時(shí),前面的數(shù)組將會(huì)后面相同鍵值的數(shù)組元素
示例2
用foreach循環(huán)賦值的方法
$a = [ 1=>'a', 2=>'b', 3=>'c' ]; $b = [ 3=>'e', 4=>'f', 5=>'a' ]; foreach ($b as $key => $val) { $a[$key] = $val; } print_r($a);
輸出:
Array ( [1] => a [2] => b [3] => e [4] => f [5] => a )
分析:和示例1有點(diǎn)區(qū)別
用于做循環(huán)的數(shù)組$b
將會(huì)覆蓋數(shù)組$a
的元素,而且只覆蓋鍵值相同的元素
相關(guān)函數(shù):
array_merge
array_intersect
array_intersect_ukey
array_intersect_uassoc
array_intersect_key
array_intersect_assoc
相關(guān)學(xué)習(xí)推薦:PHP編程從入門到精通