alvery
alvery

Reputation: 1983

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?

Upvotes: 2

Views: 63

Answers (2)

J. Pichardo
J. Pichardo

Reputation: 3115

You should try two functions:

Probably you want something like

$finalArray = array();
foreach($arInitial as $array){
    $finalArray = array_merge($finalArray, $array);
}

var $finalArray = array_unique($finalArray , SORT_NUMERIC);

That way you should get the result you want.

Upvotes: 1

Kevin
Kevin

Reputation: 41885

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;
        }
    }
}

Upvotes: 4

Related Questions