note 85957 added to function.sort
| From: | lucazd at gmail dot com | Date: | Fri, 26 Sep 2008 08:04:22 +0000 |
| Subject: | note 85957 added to function.sort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-144729@lists.php.net to get a copy of this message | ||
Please, think twice before creating (and posting) your homemade solution for ordering an array by a
field.
PHP already has a solution for this; usort, which is about x40 faster than any other solution.
If creating a callback for each case hurts, you can do something like this:
<?php
/**
* @author Lucas Dománico
*/
class util {
static private $sortfield = null;
static private $sortorder = 1;
static private function sort_callback(&$a, &$b) {
if($a[self::$sortfield] == $b[self::$sortfield]) return 0;
return ($a[self::$sortfield] < $b[self::$sortfield])? -self::$sortorder : self::$sortorder;
}
static function sort(&$v, $field, $asc=true) {
self::$sortfield = $field;
self::$sortorder = $asc? 1 : -1;
usort($v, array('util', 'sort_callback'));
}
}
# Usage:
for($i=0; $i<1000 ;$i++) {
$v[] = array('score'=>rand(1,10000));
}
util::sort($v, 'score');
?>
----
Server IP: 201.216.232.3
Probable Submitter: 190.139.65.244
----
Manual Page -- http://www.php.net/manual/en/function.sort.php
Edit -- https://master.php.net/note/edit/85957
Del: integrated -- https://master.php.net/note/delete/85957/integrated
Del: useless -- https://master.php.net/note/delete/85957/useless
Del: bad code -- https://master.php.net/note/delete/85957/bad+code
Del: spam -- https://master.php.net/note/delete/85957/spam
Del: non-english -- https://master.php.net/note/delete/85957/non-english
Del: in docs -- https://master.php.net/note/delete/85957/in+docs
Del: other reasons-- https://master.php.net/note/delete/85957
Reject -- https://master.php.net/note/reject/85957
Search -- https://master.php.net/manage/user-notes.php