-2

I trust you are well.

I would like to try and sort this array by the score property of the object. Below is an example of the data (print_r).

Array
(
    [0] => stdClass Object
        (
            [device] => 352454530452548
            [reg] => MAM 432A
            [distance] => 823.36
            [ha_points] => 1
            [hb_points] => 235
            [hc_points] => 7.5
            [idling_points] => 111.5
            [speeding_points] => 168
            [total] => 523
            [score] => 68.239895064127
        )

    [1] => stdClass Object
        (
            [device] => 3518020541565265
            [reg] => SM** ***
            [distance] => 851.07
            [ha_points] => 14
            [hb_points] => 136
            [hc_points] => 6
            [idling_points] => 50
            [speeding_points] => 336
            [total] => 542
            [score] => 68.957730856451
        )

The score can be anything from 0 to 100 and I would like to sort them into descending order (biggest first?). To make things more complicated, although the chances are very slim it is possible to have two identical scores in which case it doesn't matter which one is first.

Any ideas?

Thanks in advance,

Paul

0

1 Answer 1

4

A simple usort will do the job.

$arrData = array(/* ... */);
usort($arrData, function($a, $b) {
    return $a->score < $b->score ? 1 : -1;
});
4
  • 2
    You need to return an integer < 1, 0 or > 1, not a boolean! Commented Jul 25, 2014 at 13:08
  • Brilliant, that worked although I had to change the return to $a->score < $b->score as it was ascending order. Much appreciated cheers! Commented Jul 25, 2014 at 13:08
  • @deceze: Thanks, forgot about that. Whoever added the - - it won't work properly, since these are floats, and the difference will be rounded. Commented Jul 25, 2014 at 13:11
  • True about the floats. You should still return three possible return states, not just 2! Commented Jul 25, 2014 at 13:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.