Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usort descending

Tags:

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

like image 556
000 Avatar asked Jan 26 '13 06:01

000


People also ask

What is usort() in PHP?

The usort() function sorts an array by a user defined comparison function. This function assigns new keys for the elements in the array. Existing keys will be removed.

How to sort PHP object array?

Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.

How do you sort an associative array in PHP?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.


1 Answers

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

like image 121
Gareth Cornish Avatar answered Sep 28 '22 12:09

Gareth Cornish