Home > php教程 > php手册 > body text

php一维数组合并的三种方式对比

WBOY
Release: 2016-06-06 20:13:47
Original
1687 people have browsed it

php数组合并有三种方式:array_merge,array_merge_recursive,+(就是数学运算符加号); 下面是一段对比的代码 $array1 = array(2,4,"color" = "red"); $array2 = array("a", "b", "color" = "green", "shape" = "trapezoid", 4); $result = array_merge($array

php数组合并有三种方式:array_merge,array_merge_recursive,+(就是数学运算符加号);
下面是一段对比的代码

    $array1 = array(2,4,"color" => "red");
    $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
    $result = array_merge($array1, $array2);
    echo "----------------array_merge---------------".PHP_EOL;
    print_r($result);
    echo "----------------+++++++++++---------------".PHP_EOL;
    print_r($array1+$array2);
    echo "----------------array_merge_recursive---------------".PHP_EOL;
    print_r(array_merge_recursive($array1,$array2));
Copy after login

结果如下所示

----------------array_merge---------------
Array
(
    [0] => 2
    [1] => 4
    [color] => green
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
----------------+++++++++++---------------
Array
(
    [0] => 2
    [1] => 4
    [color] => red
    [shape] => trapezoid
    [2] => 4
)
----------------array_merge_recursive---------------
Array
(
    [0] => 2
    [1] => 4
    [color] => Array
        (
            [0] => red
            [1] => green
        )
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
Copy after login

对比array_merge和+以及array_merge_recursive结果的”color”的值我们可以看出:
1.对于相同的字符串索引,
array_merge则会用后面的值覆盖前面出现的值;
+会用前面出现过的值覆盖后面相同的key;
array_merge_recursive则会把相同的索引放到一个数组里面,增加数组的维度;
2.对于相同的数字索引,
array_merge则会给重复的值重建索引(索引值从0开始);
+仍然是用前面出现过的值覆盖后面的值;
array_merge_recursive和array_merge的处理方法一样。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template