phpmultidimensional-arraymappingarray-mergeindexed

Map/Merge data from a flat array into the rows of a 2d array


I want to add the values of array b to array a:

$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];

Result should be:

$result = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];

I am trying this (and lots of other stuff) but don't get it.

foreach ($a as $el) {
    $i = 0; 
    $el[] = $b[$i];
    $i++;
}

Solution

  • This is not hard.

    <?php
    $a = [[1, 2],[4, 5],[7, 8]];
    $b = [3, 6, 9];
    for($i = 0; $i < count($b);$i++) {
        array_push($a[$i],$b[$i]);
    }
    ?>