首先来看看键名是string,两者区别:
代码如下:
PHP
$arr1 = array('a'=>'PHP');
$arr2 = array('a'=>'JAVA');
//如果键名为字符,且键名相同,array_merge()后面数组元素值会覆盖前面数组元素值
print_r(array_merge($arr1,$arr2)); //Array ( [a] => JAVA )
//如果键名为字符,且键名相同,数组相加会将最先出现的值作为结果
print_r($arr1+$arr2); //Array ( [a] => PHP )
?>
$arr1 = array('a'=>'PHP');
$arr2 = array('a'=>'JAVA');
//如果键名为字符,且键名相同,array_merge()后面数组元素值会覆盖前面数组元素值
print_r(array_merge($arr1,$arr2)); //Array ( [a] => JAVA )
//如果键名为字符,且键名相同,数组相加会将最先出现的值作为结果
print_r($arr1+$arr2); //Array ( [a] => PHP )
?>
如果键名是数字,两者区别:
代码如下:
PHP
$arr1 = array("C","PHP");
$arr2 = array("JAVA","PHP");
//如果键名为数字,array_merge()不会进行覆盖
print_r(array_merge($arr1,$arr2));//Array ( [0] => C [1] => PHP [2] => JAVA [3] => PHP )
//如果键名为数组,数组相加会将最先出现的值作为结果,后面键名相同的会被抛弃
print_r($arr1+$arr2);//Array ( [0] => C [1] => PHP )
?>
$arr1 = array("C","PHP");
$arr2 = array("JAVA","PHP");
//如果键名为数字,array_merge()不会进行覆盖
print_r(array_merge($arr1,$arr2));//Array ( [0] => C [1] => PHP [2] => JAVA [3] => PHP )
//如果键名为数组,数组相加会将最先出现的值作为结果,后面键名相同的会被抛弃
print_r($arr1+$arr2);//Array ( [0] => C [1] => PHP )
?>
特别要注意。关于“array_merge和数组相加的区别”上面已经阐述的很清楚了,回到我最初的问题“如何最有效的获取字符键名相同值不同的两个数组值集合呢”,不会这要对每个数组遍历吧,PHP中还有一个函数,获取你不常用:array_merge_recursive — 递归地合并一个或多个数组,如果输入的数组中有相同的字符串键名,则这些值会被合并到一个数组中去。如下例:
代码如下:
PHP
$arr1 = array("a"=>"PHP","c");
$arr2 = array("a"=>"java","c","ruby");
print_r(array_merge_recursive($arr1,$arr2));
?>
$arr1 = array("a"=>"PHP","c");
$arr2 = array("a"=>"java","c","ruby");
print_r(array_merge_recursive($arr1,$arr2));
?>
结果如下:
Array
(
[a] => Array
(
[0] => PHP
[1] => java
)
[0] => c
[1] => c
[2] => ruby
)
这样,就可以获取多个数组中键名相同的元素值集合了。