sort 2-D array or Multi-Dimensional Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
scienceskillz
Forum Newbie
Posts: 3
Joined: Thu Dec 10, 2009 10:21 pm

sort 2-D array or Multi-Dimensional Array

Post 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
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

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

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post by John Cartwright »

scienceskillz wrote:is there a built-in function like that to sort multidimensional array by one of the dimensions?
array_multisort()
Post Reply