note 30766 deleted from function.usort by crell

From: Date: Wed, 30 Mar 2022 22:13:41 +0000
Subject: note 30766 deleted from function.usort by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217815@lists.php.net to get a copy of this message
Note Submitter: skrebbel at operamail dot com ---- 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.

« previous php.notes (#217815) next »