phparraysmergeassociative-arrayarray-push

Evenly push values from a flat array into same positioned rows of a 2d array


I need to evenly/synchronously push values from my second array into the rows of my first array.

The arrays which have the same size, but with different keys and depths. The first is an array of rows and the second is a flat array.

$array1 = [
    12 => [130, 28, 1],
    19 => [52, 2, 3],
    34 => [85, 10, 5]
]

$array2 = [4, 38, 33]

Preferred result:

[
    12 => [130, 28, 1, 4],
    19 => [52, 2, 3, 38],
    34 => [85, 10, 5, 33]
]

(I would like to keep the same indices of array 1, however it is not mandatory.)

I have tried these methods, but none of them work because the first array keys are unpredictable.

$final = [];
foreach ($array1 as $idx => $val) {
    $final = [$val, $array2[$idx]];
}

Another:

foreach ($array1 as $index => $subArray) {
    $array1 [$index][] = $array2[$index];
}

Solution

  • Here is one way to do this:

    $merged = array_map('array_merge', $array1, array_chunk($array2, 1));
    $result = array_combine(array_keys($array1), $merged);
    

    The second step with array_combine is necessary to reapply the non-sequential keys because array_map won't preserve them in the first step.