Alex Veryutin Alex Veryutin - 5 months ago 22
PHP Question

Transpose convert column values of multi dimensional array into flat array

initial array is looks like this:

$arInitial = Array(
0 => Array(1,2,3),
1 => Array(3,4),
2 => Array(5,6,7,8),
3 => Array(9)
);


The resulting array should be:

Array(1,3,5,9,2,4,6,3,7,8);


I was thinking about while(1) loop, but nothing. Any ideas?

Answer

There are myriad of ways to get this, there's already a collection of array incantation function that does this, I just can't find the dup question yet, but another way is just to array_shift each batch:

$result = array();
$max = count($arInitial);
for($i = 0; $i < $max; $i++) {
    foreach($arInitial as &$a) {
        if(!empty($a)) {
            $e = array_shift($a);
            $result[] = $e;
        }
    }
}