将数组合并为多维数组

时间:2016-05-24 13:23:03

标签: php arrays

我如何以下面解释的方式合并两个数组?

使用print_r(),这是两个数组的输出; 第一个;

Array
(
    [created] => 1
    [approved] => 1
)

第二个数组;

Array
(
    [created] => Array
        (
            [label] => Order created
            [roles] => Array
                (
                    [0] => ROLE_USER
                )

            [next_states] => Array
                (
                    [approve] => Array
                        (
                            [target] => approved
                        )

                )

        )

    [approved] => Array
        (
            [label] => Order approved
            [roles] => Array
                (
                    [0] => ROLE_USER
                )

            [next_states] => Array
                (
                    [order] => Array
                        (
                            [target] => ordered
                        )

                )

        )
)

如何合并数组,以便第一个数组中的$value(可以是true或false)可以合并为第二个数组[state],如下所示(有注释)在[state])行;

Array
(
    [created] => Array
        (
            [label] => Order created
            [roles] => Array
                (
                    [0] => ROLE_USER
                )

            [next_states] => Array
                (
                    [approve] => Array
                        (
                            [target] => approved
                        )

                )
            [state] => 1    // I want to add this line here from the other array
        )

    [approved] => Array
        (
            [label] => Order approved
            [roles] => Array
                (
                    [0] => ROLE_USER
                )

            [next_states] => Array
                (
                    [order] => Array
                        (
                            [target] => ordered
                        )

                )
            [state] => 1    // I want to add this line here from the other array
        )
)

请注意,第一个数组和第二个数组中的$keys是相同的,但我想将$values添加到第二个数组中充当$values的数组中。最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

foreach($array1 as $a => $b)
    $array2[$a]['state'] = $b;

修改

我看过评论。要在第一个数组中不存在右键时将state设置为false,您可以使用以下代码。

foreach($array2 as $a => &$b)
    $b['state'] = isset($array1[$a]) && $array1[$a];

答案 1 :(得分:0)

您可以使用array_merge_recursive函数。它使用动态合并数组 DEMO Please click here

Another example