[英]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 而是$ results进行如下排序:1、2、3、11。对象进行如下排序:1、11、2、3
That's because strcmp
is for STRINGS . 这是因为
strcmp
用于STRINGS 。 That means string comparison rules apply, and 11 < 3
is TRUE
, because the strings are compared character-by-character. 这意味着将应用字符串比较规则,并且
11 < 3
为TRUE
,因为字符串是逐字符进行比较的。
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
. 按照整数规则,int(124)小于int(1234),但比string(1234)大,因为
3
小于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 以下是从http://php.net/manual/en/function.uasort.php进行的工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.