为什么这个usort()函数没有正确排序小数?

时间:2016-01-14 15:19:54

标签: php usort

为什么小数没有正确排序:

13
11
14
10
12.5
---------------------------------------------------------
descending order:
14
12.5
13
11
10

使用此代码:

class Customer {
    public $score;
    public function __construct($score) {
        $this->score = $score;
    }
}

$customers = [];
$customers[] = new Customer(13);
$customers[] = new Customer(11);
$customers[] = new Customer(14);
$customers[] = new Customer(10);
$customers[] = new Customer(12.5);

if(is_array($customers) && count($customers) > 0)
{
    foreach($customers as $customer)
    {
        echo '<div>'.$customer->score.'</div>';
    }
}

echo '<hr/>';
echo '<div>descending order:</div>';
usort($customers, function($a, $b) {
    return $b->score - $a->score;
});


if(is_array($customers) && count($customers) > 0)
{
    foreach($customers as $customer)
    {
        echo '<div>'.$customer->score.'</div>';
    }
}

3 个答案:

答案 0 :(得分:4)

将十进制0.5转换为整数会将其更改为0。将您的usort功能更改为:

usort($customers, function($a, $b) {
    if($b->score - $a->score >= 0){
        return 1;
    }
    return -1;
});

输出:

descending order:
14
13
12.5
11
10

PHP手册说:

  

警告:从比较函数返回非整数值,   比如float,会导致内部强制转换为整数   回调的回报值。因此,诸如0.99和0.1之类的值都将是   强制转换为0的整数值,这将比较这些值   相等。

答案 1 :(得分:1)

尝试

usort($customers, function($a, $b) {
    return strnatcmp($b->score,$a->score);
});

答案 2 :(得分:0)

usort($customers, function($a, $b) {
    return (int)$b->score - (int)$a->score;
});

例如,您的输入为14.9,1414.5,输出为14.9,1414.5,被视为14.9=14,14.0=1414.5=14