note 25882 added to function.uasort

From: Date: Wed, 09 Oct 2002 19:27:26 +0000
Subject: note 25882 added to function.uasort
Groups: php.notes 
Request: Send a blank email to php-notes+get-37864@lists.php.net to get a copy of this message
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing. It assumes your data is in the form of: $data = array( array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'), array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'), array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'), array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob')); Now, you want to sort on one or more cols, don't you? masort($data, 'LAST,FIRST'); or masort($data,array('FIRST','ID')); Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me. function masort(&$data, $sortby){ if(is_array($sortby)){ $sortby = join(',',$sortby); } uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\'); foreach($skeys as $key){ if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){ return($c); } } return($c); ')); } Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array". If anyone has a better way, please suggest. Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on. -- http://www.php.net/manual/en/function.uasort.php http://master.php.net/manage/user-notes.php?action=edit+25882 http://master.php.net/manage/user-notes.php?action=delete+25882 http://master.php.net/manage/user-notes.php?action=reject+25882

« previous php.notes (#37864) next »