note 36412 added to function.usort

From: Date: Wed, 08 Oct 2003 22:45:06 +0000
Subject: note 36412 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-58077@lists.php.net to get a copy of this message
First off just let me say thanks to skrebbel at operamail dot com for his excellent Banana class. I've expanded it so that you can specify an ordering sequence (ASC, DESC) on each of the fields. <?php class mdasort { 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][0]],$b[$this->aSortkeys[$i][0]]); if ($this->aSortkeys[$i][1] == "DESC") $r = $r * -1; if($r==0) { $i++; if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i); } return $r; } function sort() { if(count($this->aSortkeys)) { usort($this->aData,array($this,"_sortcmp")); } } } $B = new mdasort; $B->aData = array( array("name" => "hank", "headsize" => "small", "age" => 32), array("name" => "sade", "headsize" => "petit", "age" => 36), array("name" => "hank", "headsize" => "large", "age" => 33), array("name" => "sade", "headsize" => "large", "age" => 32), array("name" => "john", "headsize" => "large", "age" => 32), array("name" => "hank", "headsize" => "small", "age" => 36), array("name" => "hank", "headsize" => "small", "age" => 40) ); $B->aSortkeys = array( array('name','ASC'), array('headsize','DESC'), array('age','ASC'), ); $B->sort(); foreach ( $B->aData as $display_row ) { echo $display_row['name'] . ', '; echo $display_row['headsize'] . ', '; echo $display_row['age']; echo '<br>'; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+36412 Delete -- http://master.php.net/manage/user-notes.php?action=delete+36412&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+36412&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#58077) next »