note 90541 deleted from function.array-multisort by cmb

From: Date: Sun, 29 Sep 2019 07:49:37 +0000
Subject: note 90541 deleted from function.array-multisort by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212424@lists.php.net to get a copy of this message
Note Submitter: za at byza dot it ---- I wrote a function to sort a multidimensional array by multiple columns in ascending and descending order. Sample array: <?php $my_array=array( array('id'=>1, 'surname'=>'rossi', 'name'=>'mario', 'group'=>'admin'), array('id'=>2, 'surname'=>'rossi', 'name'=>'giovanni', 'group'=>'user'), array('id'=>3, 'surname'=>'verdi', 'name'=>'luigi', 'group'=>'user'), array('id'=>4, 'surname'=>'verdi', 'name'=>'franco', 'group'=>'guest'), array('id'=>5, 'surname'=>'bianchi', 'name'=>'mario', 'group'=>'guest') ); ?> Example: <?php array_sort($my_array,'!group','surname'); ?> Output: sort the array DESCENDING by group and then ASCENDING by surname. Notice the use of ! to reverse the sort order. Rows order will be: 2,3,5,4,1 The function code: <?php function array_sort_func($a,$b=NULL) { static $keys; if($b===NULL) return $keys=$a; foreach($keys as $k) { if(@$k[0]=='!') { $k=substr($k,1); if(@$a[$k]!==@$b[$k]) { return strcmp(@$b[$k],@$a[$k]); } } else if(@$a[$k]!==@$b[$k]) { return strcmp(@$a[$k],@$b[$k]); } } return 0; } function array_sort(&$array) { if(!$array) return $keys; $keys=func_get_args(); array_shift($keys); array_sort_func($keys); usort($array,"array_sort_func"); } ?>

« previous php.notes (#212424) next »