Ace Ace - 4 months ago 7
PHP Question

swap ( twist ) multidimensional array in php

i want to "twist" a 2d array by "90°"..

let me explain that.

I have an array like this:

array(
array( adam , brad , chris , david ),
array( 21 , 23 , 22 , 26 )
)


and i want to convert that into something like this:

array(
array( adam , 21 ),
array( brad , 23 ),
array( chris , 22 ),
array( david , 26 )
)


how can i do that ?

Answer

Something like this should work:

// Your array stored as $arr

$newArr = array();
for ($i = 0;$i < count($arr[0]); $i++) {
    $newArr[] = array($arr[0][$i],$arr[1][$i]);
}

EDIT: You tag sorting, but the array is already sorted, do you want sorting too?

Comments