PHP-如何在数组内合并数组 [英] PHP - How to merge arrays inside array

查看:136
本文介绍了PHP-如何在数组内合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在php中合并n个数组.我的意思是我该如何做:
array_merge(from : $result[0], to : $result[count($result)-1])

array_merge_recursive(from: $result[0], to : $result[count($result) -1])

How to merge n number of array in php. I mean how can I do the job like :
array_merge(from : $result[0], to : $result[count($result)-1])
OR
array_merge_recursive(from: $result[0], to : $result[count($result) -1])


$result是其中包含多个数组的数组,如下所示:

Where $result is an array with multiple arrays inside it like this :

$result = Array(
0 => array(),//associative array
1 => array(),//associative array
2 => array(),//associative array
3 => array()//associative array
)

我的结果是:

$result = Array(
    0 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 2
    ),
    1 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 3
    ),
    2 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 4
    ),
    3 => Array(
        "name" => "Name",
        "events" => 2,
        "types" => 2
    ),
    4 => Array(
        "name" => "Name",
        "events" => 3,
        "types" => 2
    )
)

我需要的是

$result = Array(
"name" => "name",
"events" => array(1,2,3),
"types" => array(2,3,4)
)

推荐答案

array_merge 可以参数的数量可变,因此只需 call_user_func_array 技巧,您就可以传递$result数组:

array_merge can take variable number of arguments, so with a little call_user_func_array trickery you can pass your $result array to it:

$merged = call_user_func_array('array_merge', $result);

这基本上就像您输入以下内容一样运行:

This basically run like if you would have typed:

$merged = array_merge($result[0], $result[1], .... $result[n]);

更新:

现在有了5.6,我们有了 ...运算符将数组解压缩为参数,因此您可以:

Update:

Now with 5.6, we have the ... operator to unpack arrays to arguments, so you can:

$merged = array_merge(...$result);

并且具有相同的结果. *

And have the same results. *

*只要在解压缩数组中具有整数键,结果相同,否则会出现E_RECOVERABLE_ERROR : type 4096 -- Cannot unpack array with string keys错误.

* The same results as long you have integer keys in the unpacked array, otherwise you'll get an E_RECOVERABLE_ERROR : type 4096 -- Cannot unpack array with string keys error.

这篇关于PHP-如何在数组内合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆