note 91483 deleted from function.usort by cmb
| From: | cmb@php.net | Date: | Sat, 27 Aug 2016 18:28:17 +0000 |
| Subject: | note 91483 deleted from function.usort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206402@lists.php.net to get a copy of this message | ||
Note Submitter: phpguy at lifetoward dot com
----
I recommend that you take special note of the fact that an INTEGER value must be returned from a
sorting callback function. So, let's say you want to sort arrays by a quotient of two of their
elements and to do so you write something like:
<?php
function sorter($a, $b)
{ return $a['num']/$a['denom'] - $b['num']/$b['denom']; }
?>
You may not get the result you want because probably $x['num']/$x['denom'] has
absolute value less than 1 and you'll get a lot of "same value" effective results
from the comparator function as integer rounding occurs.
To solve this just boost up the quotients to be big integers, then subtract them:
<?php
function sorter($a, $b)
{ return 1000*$a['num']/$a['denom'] -
1000*$b['num']/$b['denom']; }
?>