我目前正在尝试按其子值对多维数组进行排序。 数组的结构是:
[0] => Array
(
[id] => 87
[sold] => 50
[stock] => 991
[speed] => 1.5
[days_left] => 660.66666666667
)
[1] => Array
(
[id] => 97
[sold] => 20
[stock] => 120
[speed] => 1.2
[days_left] => 100
)
[2] => Array
(
[id] => 36
[sold] => 2
[stock] => 1020
[speed] => 1.02
[days_left] => 1000
)
我正在使用的代码是:
usort($data, function($a, $b) { return $a[$_GET['sortby']] - $b[$_GET['sortby']]; });
$ _GET ['sortby']变量等于键。
到目前为止一切顺利,正常工作,除了速度之外,它还能正确排序所有值! 首先,我认为它与十进制数有关,但days_left也包含小数,并且排序正确..:/
更正输出(days_left):
[0] => Array
(
[id] => 97
[sold] => 20
[stock] => 120
[speed] => 1.2
[days_left] => 100
)
[1] => Array
(
[id] => 87
[sold] => 50
[stock] => 991
[speed] => 1.5
[days_left] => 660.66666666667
)
[2] => Array
(
[id] => 36
[sold] => 2
[stock] => 1020
[speed] => 1.02
[days_left] => 1000
)
输出错误(速度):
[0] => Array
(
[id] => 97
[sold] => 20
[stock] => 120
[speed] => 1.2
[days_left] => 100
)
[1] => Array
(
[id] => 87
[sold] => 50
[stock] => 991
[speed] => 1.5
[days_left] => 660.66666666667
)
[2] => Array
(
[id] => 36
[sold] => 2
[stock] => 1020
[speed] => 1.02
[days_left] => 1000
)
希望有人可以帮助我!
答案 0 :(得分:34)
请参阅usort文档。浮点结果将转换为整数。要正确工作,请使用以下代码:
usort(
$data,
function($a, $b) {
$result = 0;
if ($a[$_GET['sortby']] > $b[$_GET['sortby']]) {
$result = 1;
} else if ($a[$_GET['sortby']] < $b[$_GET['sortby']]) {
$result = -1;
}
return $result;
}
);
答案 1 :(得分:0)
The PHP doc has a comment that has the solution to this problem. A big thanks to that guy.
这是一个用十进制数对多维数组进行排序的函数:
function usortWithFloatVals() {
$arguments = func_get_args();
$array = $arguments[0];
$code = '';
for ($c = 1; $c < count($arguments); $c += 2) {
if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
$code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
if ($arguments[$c + 1] == "ASC") {
$code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
}
else {
$code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
}
}
}
$code .= 'return 0;';
$compare = create_function('$a,$b', $code);
usort($array, $compare);
return $array;
}
使用它就像使用usort()
:
usortWithFloatVals($data, function($a, $b) {
return ($a[$_GET['sortby']] - $b[$_GET['sortby']]) ? 1 : -1;
});
答案 2 :(得分:0)
尝试 strnatcmp():
usort($output, function($a, $b) {
return strnatcmp($b->days_left, $a->days_left);
});
答案 3 :(得分:0)
如果有人想要更简洁的代码
使用 ceil
会将分数四舍五入并对小数进行正确排序
usort($data, function($a, $b)
{
return ceil($a[$_GET['sortby']] - $b[$_GET['sortby']]);
});