php中的array_merge和“+”的区别

来源:互联网 发布:愿你知我心 编辑:程序博客网 时间:2024/04/28 23:59

array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。 

<?php
$array1 
= array("color" => "red"24);
$array2 = array("a""b""color" => "green""shape" => "trapezoid"4);
$result array_merge($array1$array2);
print_r($result);
?>

以上例程会输出:

Array(    [color] => green    [0] => 2    [1] => 4    [2] => a    [3] => b    [shape] => trapezoid    [4] => 4)



In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1
[0] ="zero";
$array1[1] ="one";

$array2[1] ="one";
$array2[2] ="two";
$array2[3] ="three";

$array3 = $array1+$array2;

//This will result in::

//$array3 = array(0=>"zero",1=>"one",2=>"two",3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian

0 0