phparraysmultidimensional-arraymerge

Re-cycle an array as needed to populate a new column in a 2d array


I have a 2d array and a flat array which need to be merged in a special way.

$arr1 = [
    ['a'],
    ['b'],
    ['c'],
    ['d'],
    ['e'],
];

$arr2 = ['1', '2'];

Output should be

[
    ['a', 1],
    ['b', 2],
    ['c', 1],
    ['d', 2],
    ['e', 1],
]

How do I continuously access the elements of the second array to fill add the new column to the first array?


Solution

  • This version will allow $arr2 to contain any number of values, should that be a requirement:

    <?php
    
    $arr1 = [
        ['a'], ['b'], ['c'], ['d'], ['e'],
    ];
    
    $arr2 = ['1', '2'];
    
    // wrap the array in an ArrayIterator and then in an 
    // InfiniteIterator - this allows you to continually
    // loop over the array for as long as necessary
    
    $iterator = new InfiniteIterator(new ArrayIterator($arr2));
    $iterator->rewind(); // start at the beginning
    
    // loop over each element by reference
    // push the current value in `$arr2` into 
    // each element etc.
    foreach ($arr1 as &$subArray) {
        $subArray[] = $iterator->current();
        $iterator->next();
    }
    
    print_r($arr1);
    

    This yields:

    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => 1
            )
    
        [1] => Array
            (
                [0] => b
                [1] => 2
            )
    
        [2] => Array
            (
                [0] => c
                [1] => 1
            )
    
        [3] => Array
            (
                [0] => d
                [1] => 2
            )
    
        [4] => Array
            (
                [0] => e
                [1] => 1
            )
    
    )
    

    Hope this helps :)