phparraysmultidimensional-arrayconcatenationprepend

Prepend strings from a flat array to the corresponding elements of each row of a 2d array


I have two arrays:

First:

Array
(
    [0] => Catalog No.:
    [1] => H-B No.
)

Second array:

Array
(
    [0] => Array
        (
            [0] => GG
            [1] => 692
        )

    [1] => Array
        (
            [0] => VV
            [1] => 693
        )

)

I want o to merge them into one array to get this:

 Array
    (
        [0] => Array
            (
                [0] => Catalog No.: GG
                [1] => H-B No. 692
            )
    
        [1] => Array
            (
                [0] => Catalog No.: VV
                [1] => H-B No. 693
            )
    
    )

I tried with array merge, but that works with keys and values, I want to merge only values from this two arrays into one.


Solution

  • <?php
    
    $first = ['Catalog No.:', 'H-B No.'];
    $second = [['GG', 692],['VV', 693]];
    $result = [];
    
    foreach ($second as $key => $values) {
        foreach ($values as $number => $value) {
            if (!isset($first[$number])) {
                continue;
            } 
    
            $result[$key][] = $first[$number] . ' ' . $value;
        }
    }
    
    var_dump($result);