BMBM
BMBM

Reputation: 16033

sort objects, some should always be first

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');

Upvotes: 2

Views: 110

Answers (2)

pakore
pakore

Reputation: 11497

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);
}

Upvotes: 4

phimuemue
phimuemue

Reputation: 36071

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.

Upvotes: 0

Related Questions