简体   繁体   中英

Usort in php returns messed up result

Object before:

    0 => 
        object(stdClass)[130]
          public 'id' => int 17
          public 'account_id' => int 18
          public 'rank' => int 1
          public 'skill' => string '0.0000' (length=6)
      1 => 
        object(stdClass)[131]
          public 'id' => int 33
          public 'account_id' => int 19
          public 'levels' => int 0
          public 'rank' => int 3
          public 'skill' => string '0.0000' (length=6)
      2 => 
        object(stdClass)[132]
          public 'id' => int 23
          public 'account_id' => int 24
          public 'rank' => int 2
          public 'skill' => string '0.0000' (length=6)
3 => 
        object(stdClass)[133]
          public 'id' => int 23
          public 'account_id' => int 24
          public 'rank' => int 11
          public 'skill' => string '0.0000' (length=6)

I am using the following function

usort($results, function($a, $b)
        {
            return strcmp($a->rank, $b->rank);
});

Instead $results to get sorted like this: 1, 2, 3, 11. The object gets sorted like this: 1, 11, 2, 3

That's because strcmp is for STRINGS . That means string comparison rules apply, and 11 < 3 is TRUE , because the strings are compared character-by-character.

eg

1234
==<*
124

by integer rules, int(124) is less than int(1234), but is BIGGER than string(1234), because 3 is smaller than 4 .

Try just

return $a->rank - $b->rank;

for the comparison function.

php > var_dump(strcmp('123', '1234'));   
int(-1)  <--"less than"
php > var_dump(strcmp('124', '1234'));
int(1)   <-- "greater than"
php > var_dump(strcmp(123, 1234));
int(-1)
php > var_dump(strcmp(124, 1234));
int(1)
usort($results, function($a, $b)
        {
            if ($a->rank == $b->rank) {
                return 0;
            }
            return ($a->rank < $b->rank) ? -1 : 1;
        });

The following does the job, from http://php.net/manual/en/function.uasort.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM