3

How do I sort an array with the highest points?

Example:

$sale = array();

Array
(
   [UserA] => Array
        (
            [unsuccessful] => 0
            [Points] => 31
            [procesing] => 4
        )
   [UserB] => Array
        (
            [unsuccessful] => 4
            [Points] => 200
            [procesing] => 1
        )
   [UserC] => Array
        (
            [unsuccessful] => 3
            [Points] => 150
            [procesing] => 55
        )
)

Sort by points, it should be in order: UserB, UserC, UserA

3 Answers 3

7
uasort($array, function($a, $b) {
    return $b['Points'] - $a['Points'];
});

The uasort() and usort() functions take a callback that should specify exactly what makes one item greater or lower than another item. If this function returns 0, then the items are equal. If it returns a positive number, then the second item is greater than the first item. Else, the first item is greater than the second.

The difference between uasort() and usort() is that uasort() also keeps the keys, while usort() does not. Also take a look at the comparison of array sorting functions to find out about all the other ways you can sort arrays.

2
  • You can simplify the actual comparison using return $a['Points'] - $b['Points']. Commented Aug 2, 2011 at 15:12
  • @Stefan Gehrig, great idea, thanks. It's $b - $a though, since the results should be sorted in descending order.
    – rid
    Commented Aug 2, 2011 at 15:18
1

You can use the php function usort to provide your own custom sorting logic. See http://www.php.net/manual/en/function.usort.php

1

You may find USort helpful:

http://php.net/manual/en/function.usort.php

Also this other article on SO.

Sort multi-dimensional array with usort

Not the answer you're looking for? Browse other questions tagged or ask your own question.