note 91483 added to function.usort
| From: | phpguy at lifetoward dot com | Date: | Fri, 12 Jun 2009 00:54:46 +0000 |
| Subject: | note 91483 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-156793@lists.php.net to get a copy of this message | ||
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']; }
?>
----
Server IP: 64.71.164.2
Probable Submitter: 70.231.134.116
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/91483
Del: integrated -- https://master.php.net/note/delete/91483/integrated
Del: useless -- https://master.php.net/note/delete/91483/useless
Del: bad code -- https://master.php.net/note/delete/91483/bad+code
Del: spam -- https://master.php.net/note/delete/91483/spam
Del: non-english -- https://master.php.net/note/delete/91483/non-english
Del: in docs -- https://master.php.net/note/delete/91483/in+docs
Del: other reasons-- https://master.php.net/note/delete/91483
Reject -- https://master.php.net/note/reject/91483
Search -- https://master.php.net/manage/user-notes.php