Can anyone explain how this usort actually works |
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; } 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
Website: http://tomaz.lovrec.eu
GitHub: https://github.com/slax0rr Twitter: https://twitter.com/slax0rr |
Messages In This Thread |
Can anyone explain how this usort actually works - by PaulD - 09-27-2015, 05:30 PM
RE: Can anyone explain how this usort actually works - by slax0r - 09-28-2015, 12:20 AM
RE: Can anyone explain how this usort actually works - by Narf - 09-28-2015, 02:38 AM
RE: Can anyone explain how this usort actually works - by PaulD - 09-28-2015, 03:24 AM
RE: Can anyone explain how this usort actually works - by slax0r - 09-28-2015, 04:22 AM
RE: Can anyone explain how this usort actually works - by PaulD - 09-28-2015, 04:42 AM
RE: Can anyone explain how this usort actually works - by slax0r - 09-28-2015, 04:52 AM
RE: Can anyone explain how this usort actually works - by PaulD - 09-28-2015, 05:22 AM
RE: Can anyone explain how this usort actually works - by ignitedcms - 10-01-2015, 12:09 PM
RE: Can anyone explain how this usort actually works - by PaulD - 11-09-2015, 08:15 AM
|