note 90541 added to function.array-multisort
| From: | za at byza dot it | Date: | Mon, 27 Apr 2009 17:08:25 +0000 |
| Subject: | note 90541 added to function.array-multisort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153847@lists.php.net to get a copy of this message | ||
I wrote a function to sort a multidimensional array by multiple columns in ascending and descending
order.
Sample array:
$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: 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:
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");
}
----
Server IP: 80.241.173.5
Probable Submitter: 94.160.68.201
----
Manual Page -- http://www.php.net/manual/en/function.array-multisort.php
Edit -- https://master.php.net/note/edit/90541
Del: integrated -- https://master.php.net/note/delete/90541/integrated
Del: useless -- https://master.php.net/note/delete/90541/useless
Del: bad code -- https://master.php.net/note/delete/90541/bad+code
Del: spam -- https://master.php.net/note/delete/90541/spam
Del: non-english -- https://master.php.net/note/delete/90541/non-english
Del: in docs -- https://master.php.net/note/delete/90541/in+docs
Del: other reasons-- https://master.php.net/note/delete/90541
Reject -- https://master.php.net/note/reject/90541
Search -- https://master.php.net/manage/user-notes.php