Forum Moderators: coopster

Message Too Old, No Replies

Help sorting a multidimensional array

         

Receptional Andy

12:53 pm on Apr 25, 2009 (gmt 0)



I have an array that looks something like this:


Array
(
[0] => Array
(
[score] => 50
[name] => Widget
)

[1] => Array
(
[score] => 550
[name] => Gadget
)
)

Is it possible to sort this array via the value of [score]?

I've got as far as trying to use both array_multisort and usort, without really understanding how they work ;)

Thanks for any pointers :)

cameraman

2:23 pm on Apr 25, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



usort is a good way to do it. usort passes the outer array members to your function, and your function is supposed to return an integer that indicates whether the first argument is greater than, equal to, or less than the second argument. If you have:
function scoreAsc($a,$b) {
if($a['score'] == $b['score']) return 0;
if($a['score'] > $b['score']) return 1;
return -1;
}

usort($ary,'scoreAsc');

The function will receive, for example, $ary[0] as $a and $ary[1] as $b.

coopster

2:32 pm on Apr 25, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Right on, cameraman. And here are some more examples and explanations, including one that shows how to parse a text file and add some extra comparison code to the function:

[webmasterworld.com...]
[webmasterworld.com...]
[webmasterworld.com...]
[webmasterworld.com...]

Receptional Andy

2:43 pm on Apr 25, 2009 (gmt 0)



cameraman, this is a great help and does exactly what I need. Many thanks :)

And thanks for the links, coop :)

[edited by: Receptional_Andy at 2:44 pm (utc) on April 25, 2009]