views:

48

answers:

2

I have a collection of country objects that look like this:

class country {
    public $uid;
    public $name;
}

Now I should sort them. One country with id == 999 should always be first in the collection, the rest should be sorted by name. So, I thought usort should actually do the trick, but the sorting is not correct. I tried this:

function mySortCallback($a, $b) {
    if($a->uid == 999 || $b->uid == 999) return 1;
    return strcmp($a->name, $b->name);
}

usort($myCollection, 'mySortCallback');
A: 

The line

if($a->uid == 999 || $b->uid == 999) return 1;

can't be correct in my opinion.

Try to exchange it to check whether actually just one of the two has uid==999 and return the value according to which of them has value 999.

phimuemue
+4  A: 

strcmp:

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.0 if they are equal.

Try this:

private function mySortCallback($a, $b) {
    if ($a->uid == 999)
        return -1;
    elseif ($b->uid == 999)
        return 1;
    else
        return strcmp($a->name, $b->name);
}
pakore
Thanks, that did it, I´ll accept your answer as soon as the system allows me to do so. ;)
Max
I would suggest adding one condition if they both are `== 999` so it returns 0. That way all conditions are covered...
ircmaxell
ircmaxell that's case is undefined. I thought about it but, doing what you propose could end up not having the countries with id==999 at the beginning. This depends on the implementation of the sorting algorithm.
pakore
Well, no, they would still be at the beginning since they are "greater" than everything else. Perhaps just a first condition: `if ($a->uid == $b->uid `. That way, all 999's will be at the top of the list and sorted by name. But then again, the OP said one country, so in either case it may be moot...
ircmaxell
@ircmaxell if I understand the requirement that uid=999 should come first, then sorted by name (for all uid's), that condition is wrong; a correct one would be: `return ($a->uid != $b->uid `
manixrock
@pakore your example will not sort the items with uid=999 by name, which I assume is needed.
manixrock
@manixrock well, you are assuming it. The problem with assumptions is that they may be wrong. For me that case is undefined, as it was not stated in the question as a requirement. The user accepted the solution so I assume ;) that he is happy with the solution.
pakore