数组排序是比较常见的功能,比如在获取数据必须根据id倒序是,显示又必须要按照正序就要二次排序,场景比如聊天信息的获取,在聊天框中实时获取最新数据就这样。还有其他情况,比如按某个数值的大小进行排序等。
这个函数比较好用,不用记录太多,不过只能对某个键key进行排序,不能同时处理多个数组(多个直接用array_multisort()函数):
/** * 二维码数组排序 * @param $array array 数组 * @param $keys string 需要排序的键名 * @param string $type 排序类型,asc-正序,desc-倒序 * @return array */ function array_sort($array, $keys, $type='asc'){ $keysvalue = $new_array = array(); foreach ($array as $k => $v){ $keysvalue[$k] = $v[$keys]; } if($type == 'asc'){ asort($keysvalue); }else{ arsort($keysvalue); } reset($keysvalue); foreach ($keysvalue as $k => $v){ $new_array[$k] = $array[$k]; } return $new_array; } $abc = [ ['id'=>1,'n'=>'b','s'=>'b'], ['id'=>2,'n'=>'aa','s'=>'c'], ['id'=>3,'n'=>'ac','s'=>'b'], ]; print_r(array_sort($abc,'n','asc')); print_r(array_sort($abc,'id','desc')); print_r(array_sort($abc,'s','desc'));
demo运行结果:
Array ( [1] => Array ( [id] => 2 [n] => aa [s] => c ) [2] => Array ( [id] => 3 [n] => ac [s] => b ) [0] => Array ( [id] => 1 [n] => b [s] => b ) ) Array ( [2] => Array ( [id] => 3 [n] => ac [s] => b ) [1] => Array ( [id] => 2 [n] => aa [s] => c ) [0] => Array ( [id] => 1 [n] => b [s] => b ) ) Array ( [1] => Array ( [id] => 2 [n] => aa [s] => c ) [0] => Array ( [id] => 1 [n] => b [s] => b ) [2] => Array ( [id] => 3 [n] => ac [s] => b ) )
另外用自定义的usort同样可以:
usort($abc, function ($a, $b) { return $b['id'] - $a['id']; });