PHP,合并多维数组中的键

时间:2021-11-26 10:45:38

If I have an array which looks something like this:

如果我有一个看起来像这样的数组:

Array
(
    [0] => Array
    (
        [DATA] => Array
    (
        VALUE1 = 1
        VALUE2 = 2
    )
    )
    [1] => Array
    (   
        [DATA] => Array
    (
        VALUE3 = 3
        VALUE4 = 4
    )
    )
)

And would like to turn it into this:

并希望将其变成这样:

Array
(
    [0] => Array
    (
        [DATA] => Array
    (
        VALUE1 = 1
        VALUE2 = 2
        VALUE3 = 3
        VALUE4 = 4
    )
    )
)

I basically want to merge all the identical keys which are at the same level. What would be the best route to accomplish this? Could the array_merge functions be of any use?

我基本上想要合并所有相同级别的相同键。实现这一目标的最佳途径是什么? array_merge函数可以用吗?

I Hope this makes any sort of sense and thanks in advance for any help i can get.

我希望这有任何意义,并提前感谢我能得到的任何帮助。

1 个解决方案

#1


12  

You can use array_merge_recursive to merge all the items in your original array together. And since that function takes a variable number of arguments, making it unwieldy when this number is unknown at compile time, you can use call_user_func_array for extra convenience:

您可以使用array_merge_recursive将原始数组中的所有项合并在一起。并且由于该函数采用可变数量的参数,当在编译时未知此数字时使其变得难以处理,您可以使用call_user_func_array以获得额外的便利:

$result = call_user_func_array('array_merge_recursive', $array);

The result will have the "top level" of your input pruned off (logical, since you are merging multiple items into one) but will keep all of the remaining structure.

结果将修剪输入的“*”(逻辑,因为您将多个项合并为一个),但将保留所有剩余的结构。

See it in action.

看到它在行动。

#1


12  

You can use array_merge_recursive to merge all the items in your original array together. And since that function takes a variable number of arguments, making it unwieldy when this number is unknown at compile time, you can use call_user_func_array for extra convenience:

您可以使用array_merge_recursive将原始数组中的所有项合并在一起。并且由于该函数采用可变数量的参数,当在编译时未知此数字时使其变得难以处理,您可以使用call_user_func_array以获得额外的便利:

$result = call_user_func_array('array_merge_recursive', $array);

The result will have the "top level" of your input pruned off (logical, since you are merging multiple items into one) but will keep all of the remaining structure.

结果将修剪输入的“*”(逻辑,因为您将多个项合并为一个),但将保留所有剩余的结构。

See it in action.

看到它在行动。