Sorting arrays

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
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Sorting arrays

Post by aceconcepts »

hi,

I need to sort my array by values in a nested array.

Here is the structure of my array: Array ( [0] => Array ( [1] => Array ( [0] => Array ( [1] => 12 ) ) ) )

The value I want to sort by is the last value in the last array ([1]=>12)

How would I go about doing this? I've been looking at usort() but cant seem to get it to work.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Sorting arrays

Post by pickle »

array_multisort() is perfect for this sort of thing.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: Sorting arrays

Post by aceconcepts »

I am trying to sort my array by the last values in the last nested array. Using array_multisort() would you mind showing an example of how I might implement this sorting function for such an array?

I have tried many different ways of doing it and I am just getting nowhere.

Thanks for your help.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Sorting arrays

Post by Kieran Huggins »

http://php.net/usort FTW!

Code: Select all

// the callback comparison function
function acecompare($a,$b){
    if($a[1][0][1] == $b[1][0][1]) return 0;
    return ($a[1][0][1] < $b[1][0][1]) ? -1 : 1;
}
 
// the usort call
usort($your_massive_multidimensional_array, "acecompare");
Post Reply