note 97750 deleted from function.usort by crell

From: Date: Wed, 30 Mar 2022 22:20:25 +0000
Subject: note 97750 deleted from function.usort by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217822@lists.php.net to get a copy of this message
Note Submitter: xaguilars at gmail dot com ---- 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; } } ?>

« previous php.notes (#217822) next »