Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there better way to transpose a PHP 2D array? [duplicate]

Tags:

arrays

php

According to the PHP Manual, calling array_map with a NULL callback causes it to perform a "zip" function, creating an array of arrays of parallel elements from the given arrays.

For example:

array_map(NULL,array(1,2,3),array('a','b','c'));

yields

array(array(1,'a'),array(2,'b'),array(3,'c'))

This is also equivalent to transposing the array

array(array(1,2,3),array('a','b','c'))

Right now, it appears this is the closest way (using built-in functions) you can transpose an array, except that array_map takes a list of arrays, not an array of arrays.

In some code I am working on, I need to transpose an array of arrays, not a list of arrays, so I made this work-around:

call_user_func_array('array_map',array_merge(array(NULL),$array_of_arrays))

However, this feels very dirty and clumsy.

And so I ask:
Is there a better way to transpose a 2D array with PHP, aside from a custom implementation?

like image 228
Austin Hyde Avatar asked Aug 11 '10 15:08

Austin Hyde


1 Answers

Nope. That's the most elegant.

like image 60
Matt Williamson Avatar answered Sep 21 '22 15:09

Matt Williamson