Home > php教程 > php手册 > php多位数组合并的三种方式

php多位数组合并的三种方式

WBOY
Release: 2016-06-06 20:13:46
Original
1147 people have browsed it

首选说明一下这篇文章有点标题党的嫌疑,我前面写了一篇文章对比了php合并一维数组的三种方式,后来又用这三种方式都来处理了一下多维数组,奇怪的是array_merge和+都没有报错,我就以为他们也能用来处理多维数组。仔细观察了一下结果,才发现这两种方式其实

首选说明一下这篇文章有点标题党的嫌疑,我前面写了一篇文章对比了php合并一维数组的三种方式,后来又用这三种方式都来处理了一下多维数组,奇怪的是array_merge和+都没有报错,我就以为他们也能用来处理多维数组。仔细观察了一下结果,才发现这两种方式其实是来打酱油的。
请看代码

    $array1 = array(2,4,"color" => "red");
    $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
    $array3 = array("e","f","red"=>array("little"=>"little",3,5),2,4);
    $array4 = array("a","b","red"=>array("little"=>"big",4,6),8,9);
    echo "----------------array_merge---------------".PHP_EOL;
    print_r(array_merge($array3,$array4));
    echo "----------------+++++++++++++++++++++---------------".PHP_EOL;
    print_r($array3+$array4);
    echo "----------------array_merge_recursive---------------".PHP_EOL;
    print_r(array_merge_recursive($array3,$array4));
Copy after login

结果如下

----------------array_merge---------------
Array
(
    [0] => e
    [1] => f
    [red] => Array
        (
            [little] => big
            [0] => 4
            [1] => 6
        )
    [2] => 2
    [3] => 4
    [4] => a
    [5] => b
    [6] => 8
    [7] => 9
)
----------------+++++++++++++++++++++---------------
Array
(
    [0] => e
    [1] => f
    [red] => Array
        (
            [little] => little
            [0] => 3
            [1] => 5
        )
    [2] => 2
    [3] => 4
)
----------------array_merge_recursive---------------
Array
(
    [0] => e
    [1] => f
    [red] => Array
        (
            [little] => Array
                (
                    [0] => little
                    [1] => big
                )
            [0] => 3
            [1] => 5
            [2] => 4
            [3] => 6
        )
    [2] => 2
    [3] => 4
    [4] => a
    [5] => b
    [6] => 8
    [7] => 9
)
Copy after login

看完代码,我想聪明的看官您已经发现了打酱油的含义:array_merge和+把第一维数组的值都当作一个简单变量,然后用处理一维素组的方式把传进去的素组处理了一遍。
只有array_merge_recursive使用了迭代的方式处理了每一维度的素组。

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