【发布时间】:2018-11-11 05:10:11
【问题描述】:
今天我提供了这个question的答案,我写了一个脚本,但是我发现出了点问题。
这是第一个脚本
<?php
$array = array(
"0" => array (
"id" => 1204,
"custom_price" => 33.1500
),
"1" => array (
"id" => 1199,
"custom_price" => 15.83
),
"2" => array (
"id" => 1176,
"custom_price" => 16.83
)
);
usort($array, function($a, $b) {
return $a['custom_price'] - $b['custom_price'];
});
echo "<pre>";
print_r($array);
它的输出是(你也可以查看output on sandbox)
<pre>Array
(
[0] => Array
(
[id] => 1176
[custom_price] => 16.83
)
[1] => Array
(
[id] => 1199
[custom_price] => 15.83
)
[2] => Array
(
[id] => 1204
[custom_price] => 33.15
)
)
所以,我想要的输出应该类似于 (custom_price 15.83, 16.83, 33.15000) 但实际输出是 (custom_price 16.83,15.83,33.15000)。你可以看到 15.83 是 16.83 中最小的。排序结果错误
所以,当我将 custom_price 15.83 更改为 14.83 时,排序输出是正确的
<pre>Array
(
[0] => Array
(
[id] => 1199
[custom_price] => 14.83
)
[1] => Array
(
[id] => 1176
[custom_price] => 16.83
)
[2] => Array
(
[id] => 1204
[custom_price] => 33.15
)
)
我不明白发生了什么.. 对此有什么想法吗?
我的问题是:我检查了每次迭代,但无法确定问题。当 custom_price 为 15.83 时,结果是错误的。为什么?
【问题讨论】:
-
浮点值排序时需要使用
-1或0或1 -
@Ghost 当 custom_price 为 15.83 时结果是错误的。其他明智的结果是好的。我参考这个答案stackoverflow.com/questions/2699086/…
-
您的问题是您使用“-”而不是 进行比较,这会导致其他后果,由于舍入问题,您可以通过将 15.83 更改为 15.82 来获得所需的结果。请参阅下面 Nigel Ren 的完整答案。
-
@TommyBs Nigel Ren 的回答很好。我得到了答案