合并两个关联数组而无需重新索引 - PHP

时间:2016-06-22 08:57:45

标签: php indexing merge associative-array array-merge

如果没有重新索引,我如何合并2个关联数组?我不喜欢使用foreach或for循环,还有更好的主意吗?

$a1=array(555=>array('name'=>'First Name','surname'=>'Second Name'), 888=>array('name'=>'New First Name','surname'=>'New Second Name'));
$a2=array(888=>array('invite'=>false), 555=>array('invite'=>true)); 
$result=array(555=>array('name'=>'First Name','surname'=>'Second Name', 'invite'=>true), 888=>array('name'=>'New First Name','surname'=>'New Second Name', 'invite'=>false));

3 个答案:

答案 0 :(得分:6)

使用array_replace_recursive将邀请项添加到相应的源数组元素

array_replace_recursive($a1, $a2);

demo

答案 1 :(得分:0)

使用array_merge功能或$a1 + $a2

答案 2 :(得分:0)

您应该使用array_replace_recursive功能

$a1=array(555=>array('name'=>'First Name','surname'=>'Second Name'), 888=>array('name'=>'New First Name','surname'=>'New Second Name'));
$a2=array(888=>array('invite'=>false), 555=>array('invite'=>true));
print_r(array_replace_recursive($a1, $a2));

这将打印:

Array ( [555] => Array ( [name] => First Name [surname] => Second Name [invite] => 1 ) [888] => Array ( [name] => New First Name [surname] => New Second Name [invite] => ) )