gpt4 book ai didi

php - 为什么这个 usort() 函数不能正确排序小数?

转载 作者:可可西里 更新时间:2023-11-01 00:41:38 26 4
gpt4 key购买 nike

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

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.

关于php - 为什么这个 usort() 函数不能正确排序小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com