7

如何从单个数组变量合并多个数组?假设我在一个数组变量中有这个

这些都在一个变量中..
$array = array(array(1), array(2));

Array
(
    [0] => 1
)
Array
(
    [0] => 2
)

如何结束这个

Array
(
   [0] => 1
   [1] => 2
)
4

7 回答 7

19

这是 javascript 的 PHP 等价物Function#apply(从数组生成参数列表):

$result = call_user_func_array("array_merge", $input);

演示:http: //3v4l.org/nKfjp

于 2012-11-24T20:08:27.423 回答
7

这可能有效:

$array1 = array("item1" => "orange", "item2" => "apple", "item3" => "grape");
$array2 = array("key1" => "peach", "key2" => "apple", "key3" => "plumb");
$array3 = array("val1" => "lemon");

$newArray = array_merge($array1, $array2, $array3);

foreach ($newArray as $key => $value) {
  echo "$key - <strong>$value</strong> <br />"; 
}
于 2015-08-26T05:50:06.273 回答
5

PHP 5.6起,您可以使用可变参数参数解包

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

它的速度比call_user_func_array.

于 2017-09-27T21:40:32.137 回答
3

array_merge 可以完成这项工作

$array_meged = array_merge($a, $b);

评论后

如果固定索引,您可以使用:

$array_meged = array_merge($a[0], $a[1]);

更通用的解决方案:

$array_meged=array();
  foreach($a as $child){
  $array_meged += $child;
}
于 2012-11-24T19:58:45.090 回答
2

$resultArray = array_merge ($array1, $array1);

$result = array();
foreach ($array1 as $subarray) {
    $result = array_merge($result, $subarray);
}

// Here it is done

好读的东西: http: //ca2.php.net/manual/en/function.array-merge.php

递归:

http://ca2.php.net/manual/en/function.array-merge-recursive.php

于 2012-11-24T19:57:57.870 回答
1
$arr1 = array(0=>1);
$arr2 = array(0=>2);

$merged = array_merge($arr1,$arr2);
print_r($merged);
于 2012-11-24T19:58:24.030 回答
0

array_merge是你需要的。

$arr = array_merge($arr1, $arr2);

编辑:

$arr = array_merge($arr1[0], $arr1[1]);
于 2012-11-24T19:58:00.150 回答