Home  >  Article  >  Backend Development  >  PHP array sorting example code

PHP array sorting example code

WBOY
WBOYOriginal
2016-07-25 08:52:151148browse
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



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn