PHP合并并重新排序多维数组

时间:2017-11-14 12:33:32

标签: php arrays multidimensional-array

我有两个看起来像这样的PHP数组..

$array1
--------
Array
(
    [0] => Array
        (
            [0] => 64
            [1] => Apple
        )

    [1] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [2] => Array
        (
            [0] => 3
            [1] => Raisin
        )

    [3] => Array
        (
            [0] => 15
            [1] => Grape
        )

    [4] => Array
        (
            [0] => 11
            [1] => Banana
        )

    [5] => Array
        (
            [0] => 4
            [1] => Orange
        )
)

$array2
--------
Array
(

    [0] => Array
        (
            [0] => 22
            [1] => Pear
        )


    [1] => Array
        (
            [0] => 11
            [1] => Banana
        )

)

我想将数组合并在一起,但是将$ array2中的匹配项放在顶部,这样结果就像这样......

$array3
-------
Array
(

    [0] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [1] => Array
        (
            [0] => 11
            [1] => Banana
        )

    [2] => Array
        (
            [0] => 64
            [1] => Apple
        )


    [3] => Array
        (
            [0] => 3
            [1] => Raisin
        )

    [4] => Array
        (
            [0] => 15
            [1] => Grape
        )


    [5] => Array
        (
            [0] => 4
            [1] => Orange
        )
)

我不确定如何处理,我应该首先合并两个,然后尝试做一些排序,还是有更有效的方法?

1 个答案:

答案 0 :(得分:5)

获取第二个数组,然后获取第一个数组的其余部分

array_merge($arr2, array_udiff($arr1, $arr2, function($i1, $i2) {return $i1[0]-$i2[0];}));