0

I have the following usorts on an array of objects. I would expect the array to be primarily sorted by the second sort, and any ties to be sorted by the first (ie, stay where the first sort has left them).

usort($arr, function($a, $b) { return ($a->best->notout < $b->best->notout) ? 1 : (($a->best->notout > $b->best->notout) ? -1 : 0); });
usort($arr, function($a, $b) { return ($a->best->runs < $b->best->runs) ? 1 : (($a->best->runs > $b->best->runs) ? -1 : 0); });

They both work fine on their own (tested by commenting out the other one), but when used together the results are unexpected in as far as the equal results on the second sort don't either default to the first sort or return the same result as the just the second sort.

Like I say the first sort works as expected, so after a lot of fiddling around I still haven't found a satisfactory answer.

Any ideas?

worldofjr
  • 3,868
  • 8
  • 37
  • 49
  • 1
    Specifically, check out [this answer](http://stackoverflow.com/a/17365409/1338292) that discusses stable sort. – Ja͢ck Sep 15 '14 at 05:05

1 Answers1

0

You need thing called stable sort, which usort is not. You may implement it yourself if there is no such thing in a library, for example using merge sort algorithm

RiaD
  • 46,822
  • 11
  • 79
  • 123
  • What makes usort unstable, and how do I fix it? – worldofjr Sep 15 '14 at 04:14
  • They use algorithm that is not stable, you can't fix it. But you may write your own stable sort or use one usort with comparator that takes care of both notout and runs – RiaD Sep 15 '14 at 04:20