Home > Article > Backend Development > PHP array sorting example code
Share an example code of PHP array sorting, including forward sorting, reverse sorting, and natural sorting. Friends in need can refer to it.
php array sorting, code sharing. As follows: <?php /** // @param array $list 查询结果 // @param string $field 排序的字段名 // @param array $sortby 排序类型 // asc正向排序 desc逆向排序 nat自然排序 // edit by wbbs.it-home.org */ function list_sort_by($list,$field, $sortby='asc') { if(is_array($list)){ $refer = $resultSet = array(); foreach ($list as $i => $data){ $refer[$i] = &$data[$field]; switch ($sortby) { case 'asc': // 正向排序 asort($refer); break; case 'desc':// 逆向排序 arsort($refer); print_r($refer);echo '</br>'; break; case 'nat': // 自然排序 natcasesort($refer); break; } } foreach ( $refer as $key=> $val){ $resultSet[] = &$list[$key]; } return $resultSet; } return false; } $arr = array( 1 => array('id'=>1,'pid'=>0), 2 => array('id'=>2,'pid'=>1), 3 => array('id'=>3,'pid'=>1), 4 => array('id'=>4,'pid'=>3) ); $list = list_sort_by($arr,'id','desc'); print_r($list); ?> >>> For more information, please view the complete list of php array sorting methods |