Here is the clever one-liner that no one else 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 splits $b
into the same structure as $a
, then it is simple to merge them together.
If your input arrays are relatively small, a foreach()
is probably the best choice. As your input array grows in size, I believe you will find that my approach will have increasing performance benefits over foreach()
(though I'll be honest I am basing this on other similar answers I have provided and I haven't actually benchmarked this case).