我有2个数组
第一个数组
Array ( [2019-04-29] => Array ( [0] => 366 [1] => 82 [2] => 44 ) [2019-04-30] => Array ( [0] => 330 [1] => 115 [2] => 55 ) )
第二个数组
Array ( [0] => 492 [1] => 500 )
需要将这些数组与这样的输出合并。
Array ( [0] => Array ( [0] => 492 [1] => 366 [2] => 82 [3] => 44 ) [1] => Array ( [0] => 500 [1] => 330 [2] => 115 [3] => 55 ) )
请帮助。
答案 0 :(得分:1)
您可以将array_walk和array_merge与传统的增量器结合使用
array_walk($arr1, function (&$item, $key) use ($arr2,&$i) { // $i should change at memory address
$item = array_merge($item, [$arr2[$i]]);
$i++;
});
输出
Array
(
[2019-04-29] => Array
(
[0] => 366
[1] => 82
[2] => 44
[3] => 492
)
[2019-04-30] => Array
(
[0] => 330
[1] => 115
[2] => 55
[3] => 500
)
)
Demo。
答案 1 :(得分:0)
您可以使用array_walk
和array_merge
$arr1 = Array (
'2019-04-29' => Array (
'0' => 366,
'1' => 82,
'2' => 44
) ,
'2019-04-30' => Array (
'0' => 330,
'1' => 115,
'2' => 55
)
);
$arr2 = Array ( '0' => 492 ,'1' => 500 ) ;
$index = 0;
$res=[];
array_walk($arr1, function($v,$k) use (&$res,$arr2,&$index){
$res[] = array_merge(array($arr2[$index]),$v);
$index++;
});
echo '<pre>';
print_r($res);
结果
Array
(
[0] => Array
(
[0] => 492
[1] => 366
[2] => 82
[3] => 44
)
[1] => Array
(
[0] => 500
[1] => 330
[2] => 115
[3] => 55
)
)
答案 2 :(得分:0)
在使用array_merge
将foreach
重新索引为从0开始的数字索引之后,您可以使用$array1
循环和array_values
进行此操作。
$array1 = array_values($array1);
foreach ($array2 as $k => &$v) {
$v = array_merge(array($v), $array1[$k]);
}
print_r($array2);
输出:
Array
(
[0] => Array
(
[0] => 492
[1] => 366
[2] => 82
[3] => 44
)
[1] => Array
(
[0] => 500
[1] => 330
[2] => 115
[3] => 55
)
)