我们有这个数组,
<?php
$arr1=array(0,1,2,3);
$arr2=array(array(0,1,2,3));
array_push($arr1,$arr2);
echo "<pre>";
print_r($arr1);
?>
输出:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
)
预期:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 0
[5] => 1
[6] => 2
[7] => 3
)
我们尝试过 array_push($ arr1,$ arr2)
答案 0 :(得分:2)
没有内置功能。但是,您可以使用递归函数或递归迭代器轻松完成此操作,例如:
$arrayIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array2));
foreach($arrayIterator as $value) {
$array1[] = $value;
}
它可以在没有预告的情况下完成:
$flatArray = iterator_to_array(
new RecursiveIteratorIterator(new RecursiveArrayIterator($array2)),
false
);
$array1 = array_merge($array1, $flatArray);
答案 1 :(得分:1)
试试这个:
$arr1=array(0,1,2,3);
$arr2=array(array(0,1,2,3));
$result = array_merge($arr1, $arr2[0]);
echo "<pre>";
print_r($result);
你也可以这么做:
for($i=0;$i<count($arr2[0]);$i++)
{
array_push($arr1,$arr2[0][$i]);
}
echo "<pre>";
print_r($arr1);
答案 2 :(得分:1)
&#34;动态&#34;的解决方案具有array_merge_recursive
和array_walk_recursive
函数的多维数组:
$arr1 = array(0,1,2,3);
$arr2 = array(array(0,1,2,3), array(0 => array(4,5), 2));
$merged = array_merge_recursive($arr1,$arr2);
$result = [];
array_walk_recursive($merged, function($v,$k) use(&$result){
$result[] = $v;
});
var_dump($result);
输出:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 0
[5] => 1
[6] => 2
[7] => 3
[8] => 4
[9] => 5
[10] => 2
)
http://php.net/manual/en/function.array-walk-recursive.php
http://php.net/manual/en/function.array-merge-recursive.php
答案 3 :(得分:0)
array_merge($arr1,$arr2);
将有效。
答案 4 :(得分:0)
我编写的函数从任何多维数组中获取值,并在创建结果数组时使用它:
<?php
$arr1=array(0,1,2,3);
$arr2=array(array(0,1,2,3));
$arr3=array(array(array(0,1,2,3)));
function getValues($array)
{
$result = array();
if(isset($array[0]) && is_array($array[0]))
$result = getValues($array[0]);
else
{
$result = $array;
}
return $result;
}
$arr1Values = getValues($arr1);
$arr2Values = getValues($arr2);
$arr3Values = getValues($arr3);
$result = $arr1Values;
foreach($arr2Values as $value)
{
$result[] = $value;
}
foreach($arr3Values as $value)
{
$result[] = $value;
}
echo '<pre>';
print_r($result);
echo '</pre>';
结果是:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 0
[5] => 1
[6] => 2
[7] => 3
[8] => 0
[9] => 1
[10] => 2
[11] => 3
)