Is there an efficient way to change the structure of this multidimensional array? I want to group the column values.
//$arrayBefore
[[5, 4, 10], [11, 13, 15], [32, 14, 15]];
Desired result:
//$arrayAfter
[[5, 11, 32], [4, 13, 14], [10, 15, 15]];
If you're unsure of the array structure, you can also use foreach. Will work for more than 3 in each arrays with out any code modification
I've already been mocked on SO for promoting a variadic approach for this kind of question, but I think it is important to show what the clever developers of php have afforded coders to do.
The
...
(splat operator) tellsarray_map()
that a multi-dimensional (with a potentially variable number of subarrays) array is coming. The function then synchronously iterates each individual subarray.In the following code, I have commented out a method that statically names the arguments
$v1
,$v2
,$v3
used byarray_map()
. This will work for the OP's case.The line of code following the commented one, is a method that dynamically accesses the values without needing to do any variable naming. This will also be hugely flexible for any case where the structure of the multi-dimensional array changes its size/shape.
PHP Manual references:
One-liner (requires PHP5.6+): (Demo with additional examples/considerations)
Output:
You can do it based on array_column():-
Output:-https://eval.in/836310
Note:- above code will work only for this array.
More general and considering all aspects code is using
foreach()
:-Output:- https://eval.in/836313
OUTPUT: http://www.phpwin.org/s/BVxAx3