Home >Backend Development >PHP Tutorial >Examples of custom array sorting functions and sorting classes implemented in PHP
The example in this article describes the custom array sorting function and sorting class implemented in PHP. Share it with everyone for your reference, the details are as follows:
/* * 二维数组自定义排序函数 * uasort($arr,function_name) * **/ $arr = array( array('a'=>1,'b'=>'c'), array('a'=>4,'b'=>'a'), array('a'=>5,'b'=>'g'), array('a'=>7,'b'=>'f'), array('a'=>6,'b'=>'e') ); function compare_arr($x,$y){ if($x['b']<$y['b']){ return -1; }else if($x['b']>$y['b']){ return 1; }else{ return 0; } } uasort($arr,'compare_arr'); foreach($arr as $a){ echo $a['a'].'=>'.$a['b'].'<br/>'; }
Custom sorting class in the manual:
class multiSort { var $key; //key in your array //排序函数 参数依次是 数组 待排列索引 排序类型 function run ($myarray, $key_to_sort, $type_of_sort = '') { $this->key = $key_to_sort; if ($type_of_sort == 'desc') uasort($myarray, array($this, 'myreverse_compare')); else uasort($myarray, array($this, 'mycompare')); return $myarray; } //正序 function mycompare($x, $y) { if ( $x[$this->key] == $y[$this->key] ) return 0; else if ( $x[$this->key] < $y[$this->key] ) return -1; else return 1; } //逆序 function myreverse_compare($x, $y) { if ( $x[$this->key] == $y[$this->key] ) return 0; else if ( $x[$this->key] > $y[$this->key] ) return -1; else return 1; } }