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>';
}
}
解决方法:
将十进制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手册说:
Caution: Returning non-integer values from the comparison function,
such as float, will result in an internal cast to integer of the
callback’s return value. So values such as 0.99 and 0.1 will both be
cast to an integer value of 0, which will compare such values as
equal.
标签:usort,php 来源: https://codeday.me/bug/20190829/1760842.html