1

I need to turn this array:

$data = array(array('a', 'b'), array('1','2'), array('hi','bye'));

Into this one:

$final = array (array ('a', '1', 'hi'), array ('b','2','bye'));

How do I loop $data to get $final? I've been looping for hours and I cannot get it.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
lleoun
  • 477
  • 3
  • 6
  • 15

1 Answers1

5

You can use array_map in an interesting way to do this:

$data = array(array('a', 'b'), array('1','2'), array('hi','bye'));
array_unshift($data, null); /* or use the array union operator: array(null) + $data */
$result = call_user_func_array('array_map', $data);
print_r($result);

Yields:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => 1
            [2] => hi
        )

    [1] => Array
        (
            [0] => b
            [1] => 2
            [2] => bye
        )

)

Hope this helps :)

Edit

If you're interested in a breakdown of what is happening here, I've written a short blog post here

Basically, if you pass null as the first argument to array_map, you can then pass an arbitrary number of arrays to it - the function does all the rotating for you. Useful!

If you have an array of arrays (as you do) then you need some help with call_user_func_array to "unpack" the arrays.

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48
  • No problem :) It's a pretty useful (and sort of unusual) use case for `array_map` - if you go to its manual page (http://ie1.php.net/array_map) it discusses it under Example #4 – Darragh Enright Mar 31 '14 at 08:57