Home > Article > Backend Development > php multidimensional array sorting
Custom function multi-dimensional array sorting:
Function:
/** * @param array $list 要排序的数组 * @param string $sort_key 要按照排序的字段 * @param $order 排序方式,省略默认降序 降序SORT_DESC 升序 SORT_ASC * @return array 返回排序后的数组 */ function getSort($list,$sort_key,$order=SORT_DESC){ if(!is_array($list)){ return $list; } $key_array = array(); foreach($list as $v){ $key_array[] = $v[$sort_key]; } array_multisort($key_array,$order,$list); return $list; }
Usage:
<?php header('Content-type:text/html;charset=utf-8'); $list = array(      array('name'=>'张三','age'=>111,'grade'=>'60'), array('name'=>'李四','age'=>12,'grade'=>'80'), array('name'=>'王五','age'=>21,'grade'=>'50'), array('name'=>'王五','age'=>3,'grade'=>'50'), ); $list = getSort($list,'age',SORT_ASC); var_dump($list); ?>
Output result:
Copyright statement: This article is an original article by the blogger and may not be used without the blogger's permission. Reprint.
The above introduces PHP multi-dimensional array sorting, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.