时间:2021-07-01 10:21:17 帮助过:45人阅读
/* * 二维数组自定义排序函数 * 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/>'; }
手册里的自定义排序类:
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; } }