Page 1 of 1

sort 2-D array or Multi-Dimensional Array

Posted: Sun Dec 20, 2009 1:30 am
by scienceskillz
Hi. I know sort($array) will sort a 1-D array. However, is there a built-in function like that to sort multidimensional array by one of the dimensions?

for example

$myarray = array();

$myarray['fruits'] = ['apple','orange','banana'];
$myarray['expireDate'] = ['jan','march','february'];

I want to sort fruits and expireDate based on expireDate.. so this pseudo function would return:

somespecialsortfunction($myarray,'expireDate')

$myarray['fruits'] = ['apple','banana','orange'];
$myarray['expireDate'] = ['jan','february','march'];

I realize the dates are just month strings but imagine I have actual dates inside the 'expireDate' array ....

I hope I've made this clear enough...

Thanks!

SS

Re: sort 2-D array or Multi-Dimensional Array

Posted: Sun Dec 20, 2009 7:58 pm
by daedalus__
i think you are approaching this wrong. why would you put fruits and their expiration dates in separate arrays? that eliminates the relationship

Code: Select all

 
$fruits = array(array('apple', 'jan'), array('orange', 'mar'), array('banana', 'feb'));
 
it should be easier to sort that way but i don't care enough to write code to do it right now. sorry.

Re: sort 2-D array or Multi-Dimensional Array

Posted: Sun Dec 20, 2009 8:01 pm
by John Cartwright
scienceskillz wrote:is there a built-in function like that to sort multidimensional array by one of the dimensions?
array_multisort()