标签:
合并数组的两种方式:$a+$b , array_merge($a,$b)
合并索引数组使用操作符+,有重复的索引会被丢弃;使用array_merge() 重复索引会被重置,如下面这种情况:
1 php > $a = array(); 2 3 php > $b = array(1=>‘data‘); 4 5 php > $c = $a+$b; 6 7 php > $d = array_merge($a,$b); 8 9 php > var_dump($c,$d); 10 11 //输出结果 12 13 array(1) { [1] => string(4) "data" } 14 15 array(1) { [0] => string(4) "data" }
所以,当使用+来合并两个索引数组,值可能会被丢弃,而array_merge就不会,会把重复的索引重置:
1 php > $a = array(1=>‘one‘,2=>‘two‘,3=>‘three‘); 2 php > $b = array(3=>‘three‘,4=>‘four‘,5=>‘five‘); 3 php > $c = $a+$b; 4 php > $d = array_merge($a,$b); 5 php > var_dump($c,$d); 6 array(5) { 7 [1] => string(3) "one" 8 [2] => string(3) "two" 9 [3] => string(5) "three" 10 [4] => string(4) "four" 11 [5] => string(4) "five" 12 } 13 14 array(6) { 15 [0] => string(3) "one" 16 [1] => string(3) "two" 17 [2] => string(5) "three" 18 [3] => string(5) "three" 19 [4] => string(4) "four" 20 [5] => string(4) "five" 21 }
标签:
原文地址:http://www.cnblogs.com/hellodp/p/5537480.html