合并具有相同键值的数组

时间:2018-12-27 03:13:40

标签: php arrays

数组1

array(1) {
[0]=>
    array(3) {
        ["shoplist_id"]=>
        int(11)
        ["shoplist_name"]=>
        string(18) "PM_Mon_Wed_Fri_Sun"
        ["shoplist_status"]=>
        int(0)
    }
}

数组2

array(3) {
[2184]=>
        array(3) {
        ["shoplist_id"]=>
        int(11)
        ["shoplistshop_id"]=>
        int(7)
        ["shoplistshop_status"]=>
        int(0)
}
[2184]=>
    array(3) {
        ["shoplist_id"]=>
        int(11)
        ["shoplistshop_id"]=>
        int(8)
        ["shoplistshop_status"]=>
        int(0)
    }
}
[2185]=>
    array(3) {
        ["shoplist_id"]=>
        int(11)
        ["shoplistshop_id"]=>
        int(9)
        ["shoplistshop_status"]=>
        int(0)
    }
}

我想要的

array(2) {
[0]=>
    array(3) {
        ["shoplist_id"]=>
        int(11)
        ["shoplist_name"]=>
        string(18) "PM_Mon_Wed_Fri_Sun"
        ["shoplist_status"]=>
        int(0)
        array(3) {
            [0]=>
                array(2) {
                    ["shoplistshop_id"]=>
                    int(7)
                    ["shoplistshop_status"]=>
                    int(0)
                }
            [1]=>
                array(2) {
                    ["shoplistshop_id"]=>
                    int(8)
                    ["shoplistshop_status"]=>
                    int(0)
                }
            [2]=>
                array(2) {
                    ["shoplistshop_id"]=>
                    int(9)
                    ["shoplistshop_status"]=>
                    int(0)
                }
        }
    }
}

主键是shoplist_id。

我需要合并数组1和数组2,因为它们具有相同的键和值。

我尝试使用array_merge / array_merge_recursive似乎无法正常工作。

那么如何合并具有相同键和相同值的数组1和2? 那是我想念的吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以在此处使用array_merge:

$expectedOutputArray = array_merge($array1[0], $array2);

如您所见,$ array1 [0]本身是一个数组,因此它将合并并提供预期的输出。