note 38424 added to function.usort
| From: | webmaster at zeroweb dot org | Date: | Sat, 20 Dec 2003 08:05:40 +0000 |
| Subject: | note 38424 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-62262@lists.php.net to get a copy of this message | ||
Needed a quick, fairly uncluttered way of sorting an array of objects by a certain object attribute,
so here's what I came up with. Uses one global array and usort(). Also accepts an optional sort
direction argument (CSORT_ASC = sort ascending, CSORT_DESC = sort descending). Use it like this:
(assuming $myarray is your array, "index" is the attribute you want to sort by, and you
want to sort in descending order)
csort($myarray, "index", CSORT_DESC);
Hope this is of use to someone. Probably a better way to pull this off, but this works alright.
define("CSORT_ASC", 1);
define("CSORT_DESC", -1);
function csort_cmp(&$a, &$b)
{
global $csort_cmp;
if ($a->$csort_cmp['key'] > $b->$csort_cmp['key'])
return $csort_cmp['direction'];
if ($a->$csort_cmp['key'] < $b->$csort_cmp['key'])
return -1 * $csort_cmp['direction'];
return 0;
}
function csort(&$a, $k, $sort_direction=CSORT_ASC)
{
global $csort_cmp;
$csort_cmp = array(
'key' => $k,
'direction' => $sort_direction
);
usort($a, "csort_cmp");
unset($csort_cmp);
}
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38424
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38424&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38424&report=yes
Search -- http://master.php.net/manage/user-notes.php