如何使用array_merge_recursive()数组?

时间:2014-11-27 23:16:36

标签: php arrays recursion merge

我刚刚开始了解array_merge_recursive()的工作原理。

有人能告诉我如何将这个php函数与数组一起使用吗?

我正在尝试执行以下操作:

$ars[] = array("name_a" => array("color" => array("red")));
$ars[] = array("name_a" => array("color" => array("green", "blue")));
$ars[] = array("name_b" => array("color" => array("green", "tangerine")));
$ars[] = array("name_c" => array("color" => array("purple", "blue","red")));
$ars[] = array("name_c" => array("color" => array("green", "blue","green","beige")));
$ars[] = array("name_b" => array("color" => array("green", "blue","yellow")));

$result = array_merge_recursive($ars);

由于某种原因,我不知道,这是行不通的。它为我工作的唯一方式如下:

$ars1 = array("name_a" => array("post_id" => array("red")));
$ars2 = array("name_a" => array("post_id" => array("green", "blue")));
$ars3 = array("name_b" => array("post_id" => array("green", "blue")));
$ars4 = array("name_c" => array("post_id" => array("green", "blue","red")));
$ars5 = array("name_c" => array("post_id" => array("green", "blue","green","beige")));
$ars6 = array("name_b" => array("post_id" => array("green", "blue","yellow")));
$result = array_merge_recursive($ars1,$ars2,$ars3,$ars4,$ars5,$ars6);

那么,我怎样才能在array_merge_recursive();函数中放入一个数组?

2 个答案:

答案 0 :(得分:2)

如果要调用array_merge_recursive();或任何其他具有映射为args的数组的函数,可以使用:

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

从PHP 5.6开始,有一个特殊的运算符:

$result = array_merge_recursive(...$ars);

答案 1 :(得分:0)

我认为你回答了你自己的问题吗?

array_merge_recursive()需要两个数组类型的参数,以便您可以" merge"他们。你究竟与一个数组合并了什么?