当前位置: 首页 > 后端技术 > PHP

php数组合并与加法

时间:2023-03-29 19:24:01 PHP

背景php合并数组有两种方式:array_merge和arr+arr,区别如下:对于关联数组,如果有相同的key,array_merge从后面覆盖前面,arr+arr是封面后面的正面。对于索引数组,如果有相同的key,array_merge会追加追加但不会覆盖;arr+arr是在之前的overwrite之后进行索引重排,array_merge会重新排列数值索引,arr+arr不是常见的使用场景1.Associativearraymerge//默认配置$defaultConfig=['timeout'=>1];//customconfiguration$inputParam=['timeout'=>2];//用自定义配置覆盖默认配置$merged=array_merge($defaultConfig,$inputParam);2.合并索引数组,保留原索引$userMap1=[//Userinformation'111'withuid111=>[...]//Userinformation'112'=uid112=>[...]];$userMap2=[//Userinformation'222'withuid222=>[...]];//需要合并以上两个用户信息,如果使用array_merge,数字会重新排列Index,导致丢失uid的,此时使用arr+arr是一个不错的选择$combinedUserMap=$userMap1+$userMap2