PHP:两个数组合并,相同键名的值相加

1
2
3
4
5
6
7
$array1 = array('a'=>1,'b'=>2);
$array2 = array('b'=>1,'c'=>5,'d'=>4);
foreach ((array)array_intersect(array_keys($array1),array_keys($array2)) as $key){
$mixed[$key] = $array1[$key]+$array2[$key];
unset($array1[$key],$array2[$key]);
}
$mixed = array_merge($array1,$array2,(array)$mixed);