-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

Smithey93
  • 45
  • 1
  • 13

1 Answers1

2

A simple usort will do the job.

$arrData = array(/* ... */);
usort($arrData, function($a, $b) {
    return $a->score < $b->score ? 1 : -1;
});
Vlad Preda
  • 9,182
  • 6
  • 31
  • 62
  • 2
    You need to return an integer < 1, 0 or > 1, not a boolean! – deceze Jul 25 '14 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! – Smithey93 Jul 25 '14 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. – Vlad Preda Jul 25 '14 at 13:11
  • True about the floats. You should still return *three* possible return states, not just 2! – deceze Jul 25 '14 at 13:12