我有2个数组,我尝试将它组合起来,因为它具有相同长度的关键buut我变成了一个错误。这是我的阵列:
$arary1 = array(0=>array(0=>1, 1=>2, 2=>3),
1=>array(0=>1, 1=>2, 2=>3),
2=>array(0=>1, 1=>2, 2=>3)
);
$array2 = array(
array(0=>
array(0=>4, 1=>5, 2=>6, 3=>7, 4=>8),
array(0=>9, 1=>10, 2=>11, 3=>12, 4=>13),
array(0=>14, 1=>15, 2=>16)),
array(1=>
array(0=>4, 1=>5, 2=>6, 3=>7, 4=>8),
array(0=>9, 1=>10, 2=>11, 3=>12, 4=>13),
array(0=>14, 1=>15, 2=>16)),
array(2=>
array(0=>4, 1=>5, 2=>6, 3=>7, 4=>8),
array(0=>9, 1=>10, 2=>11, 3=>12, 4=>13),
array(0=>14, 1=>15, 2=>16))
);
在这里你可以看到我想要的东西:
$newarray = array(
array(0=>
array(0=>1, 1=>2, 2=>3),
array(0=>4, 1=>5, 2=>6, 3=>7, 4=>8),
array(0=>9, 1=>10, 2=>11, 3=>12, 4=>13),
array(0=>14, 1=>15, 2=>16)),
array(1=>
array(0=>1, 1=>2, 2=>3),
array(0=>4, 1=>5, 2=>6, 3=>7, 4=>8),
array(0=>9, 1=>10, 2=>11, 3=>12, 4=>13),
array(0=>14, 1=>15, 2=>16)),
array(2=>
array(0=>1, 1=>2, 2=>3),
array(0=>4, 1=>5, 2=>6, 3=>7, 4=>8),
array(0=>9, 1=>10, 2=>11, 3=>12, 4=>13),
array(0=>14, 1=>15, 2=>16))
);
我的阵列是动态的,但 $ array1 和 $ array2 的长度是相同的。有人可以帮助我吗?
答案 0 :(得分:1)
您可以使用array_map
循环遍历数组并使用array_merge
合并2个数组。
$arary1 = ...
$array2 = ...
$newarray = array_map(function ($a, $b) {
return array_merge(array($a),$b);
}, $arary1, $array2 );
echo "<pre>";
print_r( $newarray );
echo "</pre>";
这将导致:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 7
[4] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
[4] => 13
)
[3] => Array
(
[0] => 14
[1] => 15
[2] => 16
)
)
[1] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 7
[4] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
[4] => 13
)
[3] => Array
(
[0] => 14
[1] => 15
[2] => 16
)
)
[2] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 7
[4] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
[4] => 13
)
[3] => Array
(
[0] => 14
[1] => 15
[2] => 16
)
)
)
或使用foreach
循环
$newarray = array();
foreach( $arary1 as $key => $val ) {
$newarray[] = array_merge(array($val),$array2[$key]);
}