php 降序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14534672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:28:02  来源:igfitidea点击:

usort descending

phparrayssortingmultidimensional-arrayusort

提问by 000

When i try to apply the below code from here

当我尝试从这里应用以下代码

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

it gives me results in ascending order.

它给了我升序的结果。

Output:

输出

0
0
0
0
0
0.29
1.09
6.33

On swapping $a and $b it gives the results in descending order except one value

在交换 $a 和 $b 时,它以降序给出结果,除了一个值

usort($myArray, function($a, $b) {
    return $b['order'] - $a['order'];
});

Output:

输出

6.33
1.09
0
0
0
0
0.29
0

i want to have the results in the below order:

我想按以下顺序获得结果:

6.33
1.09
0.29
0
0
0
0
0

How do i achieve the same.?

我如何实现相同的目标。?

回答by Gareth Cornish

My first guess is that usort expects an integer response, and will round off your return values if they are not integers. In the case of 0.29, when it is compared to 0, the result is 0.29 (or -0.29), which rounds off to 0. For usort, 0 means the two values are equal.

我的第一个猜测是 usort 期望一个整数响应,如果它们不是整数,它将舍入您的返回值。在 0.29 的情况下,当它与 0 比较时,结果为 0.29(或 -0.29),四舍五入为 0。对于 usort,0 表示两个值相等。

Try something like this instead:

试试这样的:

usort($myArray, function($a, $b) {
    if($a['order']==$b['order']) return 0;
    return $a['order'] < $b['order']?1:-1;
});

(I think that's the correct direction. To reverse the order, change the <to >)

(我认为这是正确的方向。要颠倒顺序,请将 更改<>

回答by Chris Charlwood

Just switch the $a and $b around as follows;

只需按如下方式切换 $a 和 $b 即可;

function sort($a, $b){ 
return strcasecmp($b->order, $a->order);
}
usort($myArray, "sort");

回答by Frits

You can also simply reverse the array once it has been sorted.

您也可以在排序后简单地反转数组。

Starting the same way you did:

以与您相同的方式开始:

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

and then reversing the results like this:

然后像这样反转结果:

$myArray = array_reverse($myArray);

回答by Jimmy B.

I know this is old, but hopefully this helps someone. Easiest way to set descending order, is to just multiply by negative one (-1) as shown below. Worked well for me, with text.

我知道这很旧,但希望这对某人有所帮助。设置降序的最简单方法是乘以负一 (-1),如下所示。对我来说效果很好,有文字。

function DESC($a, $b)
{
    return strcmp($a["text"], $b["text"])*-1;
}

usort($results,"DESC");

回答by DazBaldwin

using the space ship operator in php 7:

在 php 7 中使用太空船操作符:

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});

would return the array sorted in ascending order. reversing the comparison will return it in descending.

将返回按升序排序的数组。反转比较将以降序返回。

usort($myArray, function($a, $b) {
    return $b['order'] <=> $a['order'];
});