Welcome Guest, Not a member yet? Register   Sign In
Can anyone explain how this usort actually works
#2

(This post was last modified: 09-28-2015, 12:22 AM by slax0r.)

Hi,

this is pretty simple, is it not?
Quote:The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

So if your mathematical operation results in a result less/equal/greater than zero, your array will be sorted accordingly. If I take
your example, you have the "search_rank" of 0 and 3, and if both results are in your array in that order it means it will return -2 on the first iteration, swapping those two elements. Which can lead to unpredictable results. If you want to sort based on that rank, you should compare the values, not subtract them, as in:
PHP Code:
if ($a["search_rank"] === $b["search_rank"]) { return 0; }
return 
$a["search_rank"] < $b["search_rank"] ? -1

This way your array will be sorted based on rank, from the one with lowest value to the one with highest, if you want it the other way around, just swap the "-1" and "1" in the second line of above code snippet.

Regards
Reply


Messages In This Thread
RE: Can anyone explain how this usort actually works - by slax0r - 09-28-2015, 12:20 AM



Theme © iAndrew 2016 - Forum software by © MyBB