Home  >  Article  >  Backend Development  >  Introduction to the method of sorting arrays by multiple fields in PHP (with code)

Introduction to the method of sorting arrays by multiple fields in PHP (with code)

不言
不言forward
2019-03-25 09:29:583271browse

This article brings you an introduction to the method of sorting arrays by multiple fields in PHP (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

The closest thing I encountered was a two-dimensional array that needed to be sorted by inventory, and then sorted by store distance.

I discovered such a method:

$array1 = array(
      0=>array('id'=>8,'name'=>'Apple','age'=> 18),
      1=>array('id'=>8,'name'=>'Bed','age'=>17),
      2=>array('id'=>5,'name'=>'Cos','age'=>16),
      3=>array('id'=>5,'name'=>'Cos','age'=>14)
);
function sortArrByManyField(){
  $args = func_get_args(); // 获取函数的参数的数组
  if(empty($args)){
    return null;
  }
  $arr = array_shift($args);
  if(!is_array($arr)){
    throw new Exception("第一个参数不为数组");
  }
  foreach($args as $key => $field){
    if(is_string($field)){
      $temp = array();
      foreach($arr as $index=> $val){
        $temp[$index] = $val[$field];
      }
      $args[$key] = $temp;
    }
  }
  $args[] = &$arr;//引用值
  call_user_func_array('array_multisort',$args);
  return array_pop($args);
}
$arr = sortArrByManyField($array1,'id',SORT_ASC,'name',SORT_ASC,'age',SORT_DESC);
print_r($arr);

The results are as follows:

array(4) {
      [0]=>array(3) {
            ["id"]=>int(5)
            ["name"]=>string(3) "Cos"
            ["age"]=>int(16)
          }
      [1]=>array(3) {
            ["id"]=>int(5)
            ["name"]=>string(3) "Cos"
            ["age"]=>int(14)
          }
      [2]=>array(3) {
            ["id"]=>int(8)
            ["name"]=>string(5) "Apple"
            ["age"]=>int(18)
          }
      [3]=>array(3) {
            ["id"]=>int(8)
            ["name"]=>string(3) "Bed"
            ["age"]=>int(17)
      }
    }

This article is over here, you can pay attention to more other exciting content The php video tutorial column of the PHP Chinese website!

The above is the detailed content of Introduction to the method of sorting arrays by multiple fields in PHP (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete