note 105764 added to function.usort

From: Date: Tue, 13 Sep 2011 13:09:10 +0000
Subject: note 105764 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-183132@lists.php.net to get a copy of this message
this is a new multisort function for sorting on multiple subfield like it will be in sql : 'ORDER BY field1, field2' number of sort field is undefined <?php $array[] = array('soc' => 3, 'code'=>1); $array[] = array('soc' => 2, 'code'=>1); $array[] = array('soc' => 1, 'code'=>1); $array[] = array('soc' => 1, 'code'=>1); $array[] = array('soc' => 2, 'code'=>5); $array[] = array('soc' => 1, 'code'=>2); $array[] = array('soc' => 3, 'code'=>2); //usage print_r(multiSort($array, 'soc', 'code')); function multiSort() { //get args of the function $args = func_get_args(); $c = count($args); if ($c < 2) { return false; } //get the array to sort $array = array_splice($args, 0, 1); $array = $array[0]; //sort with an anoymous function using args usort($array, function($a, $b) use($args) { $i = 0; $c = count($args); $cmp = 0; while($cmp == 0 && $i < $c) { $cmp = strcmp($a[ $args[ $i ] ], $b[ $args[ $i ] ]); $i++; } return $cmp; }); return $array; } /* output: Array ( [0] => Array ( [soc] => 1 [code] => 1 ) [1] => Array ( [soc] => 1 [code] => 1 ) [2] => Array ( [soc] => 1 [code] => 2 ) [3] => Array ( [soc] => 2 [code] => 1 ) [4] => Array ( [soc] => 2 [code] => 5 ) [5] => Array ( [soc] => 3 [code] => 1 ) [6] => Array ( [soc] => 3 [code] => 2 ) ) */ ---- Server IP: 89.31.146.176 Probable Submitter: 81.252.182.61 ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/105764 Del: integrated -- https://master.php.net/note/delete/105764/integrated Del: useless -- https://master.php.net/note/delete/105764/useless Del: bad code -- https://master.php.net/note/delete/105764/bad+code Del: spam -- https://master.php.net/note/delete/105764/spam Del: non-english -- https://master.php.net/note/delete/105764/non-english Del: in docs -- https://master.php.net/note/delete/105764/in+docs Del: other reasons-- https://master.php.net/note/delete/105764 Reject -- https://master.php.net/note/reject/105764 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183132) next »