note 38424 deleted from function.usort by cmb
| From: | cmb@php.net | Date: | Sun, 22 Sep 2019 07:56:20 +0000 |
| Subject: | note 38424 deleted from function.usort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212295@lists.php.net to get a copy of this message | ||
Note Submitter: webmaster at zeroweb dot org
----
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);
}
?>