简体   繁体   中英

Merge two associative arrays without reindexing - PHP

Without re-indexing how can I merge 2 associative arrays? I prefer not to use foreach or for loop, any better idea?

$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));

use array_replace_recursive to add invite items to corresponding source array elements

array_replace_recursive($a1, $a2);

demo

使用array_merge函数或$a1 + $a2

You should use array_replace_recursive function

$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));

This would print:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM