tags:

views:

371

answers:

4

I need to merge several arrays into a single array. The best way to describe what I'm looking for is "interleaving" the arrays into a single array.

For example take item one from array #1 and append to the final array. Get item one from array #2 and append to the final array. Get item two from array #1 and append...etc.

The final array would look something like this:

array#1.element#1 array#2.element#1 . . .

The "kicker" is that the individual arrays can be of various lengths.

Is there a better data structure to use?

+1  A: 

I would just use array_merge(), but that obviously depends on what exactly you do.

This would append those arrays to each other, while elements would only be replaced when they have the same non-numerical key. And that might not be a problem for you, or it might be possible to be solved because of attribute order, since the contents of the first arrays' elements will be overwritten by the later ones.

Franz
A: 

If you have n arrays, you could use a SortedList, and use arrayIndex * n + arrayNumber as a sort index.

Charles Bretana
+5  A: 

for example,

function array_zip_merge() {
    $r = array();
    for($_ = func_get_args(); count($_); $_ = array_filter($_))
     foreach($_ as &$a)
      $r[] = array_shift($a);
    return $r;
}

// test

$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
stereofrog
I like this one.
Franz
A: 

If the arrays only have numeric keys, here's a simple solution:

$longest = max( count($arr1), count($arr2) );
$final = array();

for ( $i = 0; $i < $longest; $i++ )
{
    if ( isset( $arr1[$i] ) )
        $final[] = $arr1[$i];
    if ( isset( $arr2[$i] ) )
        $final[] = $arr2[$i];
}

If you have named keys you can use the array_keys function for each array and loop over the array of keys instead.

If you want more than two arrays (or variable number of arrays) then you might be able to use a nested loop (though I think you'd need to have $arr[0] and $arr[1] as the individual arrays).

DisgruntledGoat