Sort rows in a 2d array in a descending direction by comparing a column of float values [duplicate]
Asked Answered
G

5

31

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

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.?

Gabrielson answered 26/1, 2013 at 6:57 Comment(3)
By swapping "a" and "b". Something else is wrong here.Alecalecia
that something i am unable to find..Gabrielson
maybe some of the elements are stored as strings. Try casting to some numeric type.Alecalecia
U
42

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.

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 >)

Udelle answered 26/1, 2013 at 7:5 Comment(1)
PHP needs a signum() function. BASIC had this function over 40 years ago.Topminnow
J
21

using the space ship operator in php 7 (and over):

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'];
});
Jea answered 3/12, 2019 at 11:57 Comment(0)
T
13

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

function sort($a, $b){ 
return strcasecmp($b->order, $a->order);
}
usort($myArray, "sort");
Takao answered 14/10, 2014 at 20:51 Comment(0)
N
5

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.

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

usort($results,"DESC");
Normalie answered 21/9, 2018 at 20:55 Comment(0)
B
4

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);
Burbot answered 15/7, 2016 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.