Add one array to a multidimensional array
Here we use array_walk
to achieve the desired result. Hope this will be helpful.
<?php
ini_set('display_errors', 1);
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
array_walk($a,function(&$value,$key) use($b){
array_push($value, $b[$key]);
});
print_r($a);
source to share
Here's a clever one-liner that nobody thought of:
Code: ( Demo )
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
var_export(array_map('array_merge',$a,array_chunk($b,1)));
Output:
array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
),
1 =>
array (
0 => 4,
1 => 5,
2 => 6,
),
2 =>
array (
0 => 7,
1 => 8,
2 => 9,
),
)
This approach breaks down $b
into the same structure as $a
, then just combine them together.
If your input arrays are relatively small, it is best to choose foreach()
. As your input array grows in size, I believe that you will find that my approach will have higher performance advantages over foreach()
(although I will be honest, I base this on other similar answers I have provided, and I actually haven't tested this case).
source to share