note 30766 added to function.usort
| From: | skrebbel at operamail dot com | Date: | Thu, 27 Mar 2003 19:59:07 +0000 |
| Subject: | note 30766 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-45919@lists.php.net to get a copy of this message | ||
here's another recursive multisort, however a clean and fast one that is class-based (but works
as well outside classes) and does not uglify your global namespace at all. note that strnatcmp is
used, but one could use something else of course.
btw, for arrays in which the rows/columns are 'swapped', use array_multisort().
class Banana {
var $aData;//the array we want to sort.
var $aSortkeys;//the order in which we want the array to be sorted.
function _sortcmp($a, $b, $i=0) {
$r = strnatcmp($a[$this->aSortkeys[$i]],$b[$this->aSortkeys[$i]]);
if($r==0) {
$i++;
if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i+1);
}
return $r;
}
function sort() {
if(count($this->aSortkeys)) {
usort($this->aData,array($this,"_sortcmp"));
}
}
}
$B = new Banana;
$B->aData = array(
array("name" => "hank", "headsize" => "big",
"age" => 32),
array("name" => "frank", "headsize" => "huge",
"age" => 36)
);
$B->aSortkeys = array("age","name");
$B->sort();
sorry for the ugly indenting, but i couldn't get it any better in this note adder thingo.
--
http://www.php.net/manual/en/function.usort.php
http://master.php.net/manage/user-notes.php?action=edit+30766
http://master.php.net/manage/user-notes.php?action=delete+30766
http://master.php.net/manage/user-notes.php?action=reject+30766