PHP中array_merge和array+array的区别
在PHP中可以使用array_merge函数和两个数组相加array+array的方式进行数组合并,但两者效果并不相同,区别如下:
- 当下标为数值时,array_merge()不会覆盖掉原来的值,但array+array合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖).
- 注意区别 array_merge_recursive函数
- 当下标为字符时,array+array 把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值.
演示案例:
<?php echo "<pre>"; /* ***************** * 如果key是字符串 * ***************** */ $arr1 = [ 'name' => 'zhangsan', 'age' => '28', ]; $arr2 = [ 'name' => 'lisi', 'age' => '17', ]; //如果键名为字符,且键名相同,array_merge()最后面的元素值会覆盖前面的元素值 print_r(array_merge($arr1, $arr2)); /* Array ( [name] => lisi [age] => 17 ) */ //PHP中还有一个函数:array_merge_recursive //递归地合并一个或多个数组,如果输入的数组中有相同的字符串键名,则这些值会被合并到一个数组中去 print_r(array_merge_recursive($arr1, $arr2)); /* Array ( [name] => Array ( [0] => zhangsan [1] => lisi ) [age] => Array ( [0] => 28 [1] => 17 ) ) */ //如果键名为字符,且键名相同,两个数组相加会将最先出现的元素值作为结果 print_r($arr1 + $arr2); /* Array ( [name] => zhangsan [age] => 28 ) */ //两个数组的key的个数不相同 $arr1 = [ 'name' => 'zhangsan', 'age' => '28', ]; $arr2 = [ 'name' => 'lisi', 'age' => '17', 'sex' => 'nan', ]; print_r(array_merge($arr1, $arr2)); /* Array ( [name] => lisi [age] => 17 [sex] => nan ) */ print_r($arr1 + $arr2); /* Array ( [name] => zhangsan [age] => 28 [sex] => nan ) */ echo "<hr>"; /* *************** * 如果key是数字 * *************** */ $arr1 = ['zhangsan','28']; $arr2 = ['lisi','17']; //如果键名为数字,array_merge()不会进行覆盖,但是会覆盖掉前面相同键值 print_r(array_merge($arr1,$arr2)); /* Array ( [0] => zhangsan [1] => 28 [2] => lisi [3] => 17 ) */ //如果键名为数字,数组相加会将最先出现的值作为结果,后面键名相同的会被抛弃 print_r($arr1+$arr2); /* Array ( [0] => zhangsan [1] => 28 ) */ //再比如 $arr1 = [3=>'zhangsan',9=>'28']; $arr2 = [3=>'lisi',9=>'17',12=>'nan']; //array_merge()会覆盖掉前面相同键值,重新从0开始进行键排序 print_r(array_merge($arr1,$arr2)); /* Array ( [0] => zhangsan [1] => 28 [2] => lisi [3] => 17 [4] => nan ) */ //数组相加 不会对键进行重新排序 print_r($arr1+$arr2); /* Array ( [3] => zhangsan [9] => 28 [12] => nan ) */