note 104766 added to function.usort
| From: | andreiduca at osu1 dot php dot net | Date: | Wed, 06 Jul 2011 10:37:53 +0000 |
| Subject: | note 104766 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-181276@lists.php.net to get a copy of this message | ||
The class method presented in the post below is by far the easiest method to use. Here's a
remake which allows you to sort the array ascending or descending in a more user-friendly manner:
<?php
class sortByKey {
var $key;
function __construct($key) {
$this->key = $key;
}
// comparison function for ascending order
function asc($a,$b) {
$key = $this->key;
if ($a[$key] == $b[$key]) return 0;
return (($a[$key] > $b[$key]) ? 1 : -1);
}
// comparison function for descending order
function desc($a,$b) {
$key = $this->key;
if ($a[$key] == $b[$key]) return 0;
return (($a[$key] < $b[$key]) ? 1 : -1);
}
}
// then just call (as an example)
usort($products, array(new sortByKey("price"), "desc"));
// to sort an array of products by price in descending order
?>
----
Server IP: 69.147.83.197
Probable Submitter: 86.120.65.33
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/104766
Del: integrated -- https://master.php.net/note/delete/104766/integrated
Del: useless -- https://master.php.net/note/delete/104766/useless
Del: bad code -- https://master.php.net/note/delete/104766/bad+code
Del: spam -- https://master.php.net/note/delete/104766/spam
Del: non-english -- https://master.php.net/note/delete/104766/non-english
Del: in docs -- https://master.php.net/note/delete/104766/in+docs
Del: other reasons-- https://master.php.net/note/delete/104766
Reject -- https://master.php.net/note/reject/104766
Search -- https://master.php.net/manage/user-notes.php