note 38424 modified in function.usort by thiago
| From: | thiago@php.net | Date: | Tue, 22 Jul 2008 19:16:36 +0000 |
| Subject: | note 38424 modified in function.usort by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142567@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.
<?php
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);
}
?>
--was--
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);
}
http://php.net/manual/en/function.usort.php