note 97750 added to function.usort
| From: | xaguilars at gmail dot com | Date: | Thu, 06 May 2010 11:03:29 +0000 |
| Subject: | note 97750 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168999@lists.php.net to get a copy of this message | ||
I'd like to share with the community my function for sorting an array of arrays or objects
containing associative data. This could be used, for example, with a MySQL result.
<?php
function sort_by($field, &$arr, $sorting=SORT_ASC, $case_insensitive=true){
if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) &&
isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
else $strcmp_fn = "strnatcmp";
if($sorting==SORT_ASC){
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($a->'.$field.',
$b->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($a["'.$field.'"],
$b["'.$field.'"]);
}else return 0;
');
}else{
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($b->'.$field.',
$a->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($b["'.$field.'"],
$a["'.$field.'"]);
}else return 0;
');
}
usort($arr, $fn);
return true;
}else{
return false;
}
}
?>
----
Server IP: 92.48.74.199
Probable Submitter: 79.109.240.147
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/97750
Del: integrated -- https://master.php.net/note/delete/97750/integrated
Del: useless -- https://master.php.net/note/delete/97750/useless
Del: bad code -- https://master.php.net/note/delete/97750/bad+code
Del: spam -- https://master.php.net/note/delete/97750/spam
Del: non-english -- https://master.php.net/note/delete/97750/non-english
Del: in docs -- https://master.php.net/note/delete/97750/in+docs
Del: other reasons-- https://master.php.net/note/delete/97750
Reject -- https://master.php.net/note/reject/97750
Search -- https://master.php.net/manage/user-notes.php