phpmultidimensional-arraytransposeflatteninterleave

Transpose and flatten two-dimensional indexed array where rows may not be of equal length


I would like to take an array like this and combine it into 1 single array.

array (size=2)
   0 => 
      array (size=10)
         0 => string '1' 
         1 => string 'a' 
         2 => string '3' 
         3 => string 'c' 
   1 => 
      array (size=5)
         0 => string '2'
         1 => string 'b'

However I want the array results to be interleaved.

So it would end up looking like

array
     0 => '1'
     1 => '2'
     2 => 'a'
     3 => 'b'
     4 => '3'
     5 => 'c'

I would like it so that it doesn't matter how many initial keys are passed in (this one has 2), it should work with 1, 2 or 5. Also, as you can see from my example the amount of elements most likely won't match.

Anyone know the best way to accomplish this?


Solution

  • $data = array(
        0 => array(
            0 => '1',
            1 => 'a',
            2 => '3',
            3 => 'c',
        ),
        1 => array(
            0 => '2',
            1 => 'b',
        ),
    );
    
    $newArray = array();
    $mi = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
    $mi->attachIterator(new ArrayIterator($data[0]));
    $mi->attachIterator(new ArrayIterator($data[1]));
    foreach($mi as $details) {
        $newArray = array_merge(
            $newArray,
            array_filter($details)
        );
    }
    var_dump($newArray);