PHP合并两个数组的两种方式的异同
本文讨论PHP合并数组的两种方式:$a+$b , array_merge($a,$b)
操作符+,在前一个数的基础上插入后一个数组,如果有相同的抛弃,而array_merge 是在前一个参数基础上插入后一个参数,如果有相同用的key 用后一个覆盖。
实例如下:
php > $a = array('a'=>'1','b'=>'2','c'=>'3');
php > $b = array('c'=>3,'d'=>'4','e'=>'5');
php > $c = $a+$b;
php > $d = array_merge($a,$b);
php > var_dump($c,$d);
array(5) {
'a' =>
string(1) "1"
'b' =>
string(1) "2"
'c' =>
string(1) "3"
'd' =>
string(1) "4"
'e' =>
string(1) "5"
}
array(5) {
'a' =>
string(1) "1"
'b' =>
string(1) "2"
'c' =>
int(3)
'd' =>
string(1) "4"
'e' =>
string(1) "5"
}
php > $e = array_merge($b,$a);
php > var_dump($e);
array(5) {
'c' =>
string(1) "3"
'd' =>
string(1) "4"
'e' =>
string(1) "5"
'a' =>
string(1) "1"
'b' =>
string(1) "2"
}
php > $f=$b+$a;
php > var_dump($f);
array(5) {
'c' =>
int(3)
'd' =>
string(1) "4"
'e' =>
string(1) "5"
'a' =>
string(1) "1"
'b' =>
string(1) "2"
}
当两边都是索引数组时,使用array_merge 可能会引起索引重置,如下面这种情况:
php > $a = array();
php > $b = array(1=>'data');
php > $c = $a+$b;
php > $d = array_merge($a,$b);
php > var_dump($c,$d);
array(1) {
[1] =>
string(4) "data"
}
array(1) {
[0] =>
string(4) "data"
}
所以,当使用+来合并两个索引数组,值可能会被丢弃,而array_merge就不会,会把重复的索引重置:
php > $a = array(1=>'one',2=>'two',3=>'three');
php > $b = array(3=>'three',4=>'four',5=>'five');
php > $c = $a+$b;
php > $d = array_merge($a,$b);
php > var_dump($c,$d);
array(5) {
[1] =>
string(3) "one"
[2] =>
string(3) "two"
[3] =>
string(5) "three"
[4] =>
string(4) "four"
[5] =>
string(4) "five"
}
array(6) {
[0] =>
string(3) "one"
[1] =>
string(3) "two"
[2] =>
string(5) "three"
[3] =>
string(5) "three"
[4] =>
string(4) "four"
[5] =>
string(4) "five"
}
PHP 的详细介绍:请点这里
PHP 的下载地址:请点这里