PHP-如何在数组内合并数组

如何在PHP中合并n个数组 我的意思是我怎么可以这样做的工作:

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

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

$result里面有多个数组的数组在哪里,像这样:

$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数组传递给它:

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

基本上可以像输入以下内容一样运行:

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

更新:

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

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

并具有相同的结果。*

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

以上是 PHP-如何在数组内合并数组 的全部内容, 来源链接: utcz.com/qa/408537.html

回到顶部