PHP array sorting by multiple fields implementation code

little bottle
Release: 2023-04-05 22:06:01
forward
2881 people have browsed it

This article mainly talks about the problem of using PHP language to sort arrays by multiple fields. The code is attached, friends in need can take a look.

Title:

A two-dimensional array needs to be sorted by inventory, and then sorted by store distance.

I found 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);
Copy after login

The result is as follows:


<span style="color: #008080;"> array(4) {<br>      [0]=>array(3) {<br>            ["id"]=>int(5)<br>            ["name"]=>string(3) "Cos"<br>            ["age"]=>int(16)<br>          }<br>      [1]=>array(3) {<br>            ["id"]=>int(5)<br>            ["name"]=>string(3) "Cos"<br>            ["age"]=>int(14)<br>          }<br>      [2]=>array(3) {<br>            ["id"]=>int(8)<br>            ["name"]=>string(5) "Apple"<br>            ["age"]=>int(18)<br>          }<br>      [3]=>array(3) {<br>            ["id"]=>int(8)<br>            ["name"]=>string(3) "Bed"<br>            ["age"]=>int(17)<br>      }<br>    }</span><span style="color: #008080;"><br></span>
Copy after login

[Related tutorials: PHP video tutorial]

The above is the detailed content of PHP array sorting by multiple fields implementation code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template