使用相同的键将PHP中的两个数组组合在一起

时间:2016-07-29 08:46:39

标签: php arrays

我有两个像这样的数组。



$result_1 = array(
[0] => array ("id" => "a1", "label" => "A1"),
[1] => array ("id" => "a2", "label" => "A2"));

$result_2 = array(
[0] => array ("id" => "b1", "label" => "B1"));




如何将$ result_1和$ result_2组合成一个新的数组$ result,这样它会给我一个这样的结果?



 $result = array(
[0] => array ("id" => "a1", "label" => "A1"),
[1] => array ("id" => "a2", "label" => "A2"),
[2] => array ("id" => "b1", "label" => "B1"));




如果我使用$result = array_merge($result_1,$result_2),它将只返回1个索引。如果我使用$result = array($result_1,$result_2),它将只返回2个索引。我希望它返回所有索引。请帮帮我,谢谢。

1 个答案:

答案 0 :(得分:1)

使用array_walk,因为你的result_2变量中的数组与array_push结合使用。它完成了这项工作,但请记住它会改变第一个数组http://php.net/manual/en/function.array-push.php

$result_1 = array(
    0 => array ("id" => "a1", "label" => "A1"),
    1 => array ("id" => "a2", "label" => "A2")
);

$result_2 = array(
    0 => array ("id" => "b1", "label" => "B1")
);

array_walk($result_2, function($item) use (&$result_1) {

    array_push($result_1, $result_2);
});
print_r($result_1);

Array ( 
    [0] => Array ( [id] => a1 [label] => A1 ) 
    [1] => Array ( [id] => a2 [label] => A2 ) 
    [2] => Array ( [id] => b1 [label] => B1 ) 
)