note 30766 modified in function.usort by thiago

From: Date: Tue, 22 Jul 2008 19:17:30 +0000
Subject: note 30766 modified in function.usort by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142568@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(). <?php 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 thing. --was-- 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://php.net/manual/en/function.usort.php

« previous php.notes (#142568) next »