note 20433 modified in function.asort by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 14:52:20 +0000 |
| Subject: | note 20433 modified in function.asort by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-79990@lists.php.net to get a copy of this message | ||
Here's one I whipped up to allow you to sort an array of a specific class by a member or
function:
<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
$tarr = array();
$rarr = array();
for($i = 0; $i < count($arr); $i++) {
$element = $arr[$i];
$tarr[] = strtolower($element->{$var});
}
reset($tarr);
asort($tarr);
$karr = array_keys($tarr);
for($i = 0; $i < count($tarr); $i++) {
$rarr[] = $arr[intval($karr[$i])];
}
return $rarr;
}
?>
It works very well. For example, I have a Room class with members title, isActive(), date, etc. I
can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and
it'll work.
--was--
Here's one I whipped up to allow you to sort an array of a specific class by a member or
function:
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
$tarr = array();
$rarr = array();
for($i = 0; $i < count($arr); $i++) {
$element = $arr[$i];
$tarr[] = strtolower($element->{$var});
}
reset($tarr);
asort($tarr);
$karr = array_keys($tarr);
for($i = 0; $i < count($tarr); $i++) {
$rarr[] = $arr[intval($karr[$i])];
}
return $rarr;
}
It works very well. For example, I have a Room class with members title, isActive(), date, etc. I
can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and
it'll work.
http://php.net/manual/en/function.asort.php