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?
Nope. That's the most elegant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With