Home > Backend Development > PHP Tutorial > PHP array group sorting example code

PHP array group sorting example code

WBOY
Release: 2016-07-25 09:11:58
Original
807 people have browsed it

There is the following PHP array, the contents of the array:

  1. $list = array(
  2. array(2,3,5),
  3. array(2,5,24),
  4. array(3,8,6),
  5. array(3,2,10) ,
  6. array(4,7,20),
  7. array(4,1,15),
  8. array(6,4,10),
  9. array(7,9,20),
  10. );
Copy code

For the convenience of expression, I call the three columns of numbers respectively, the three columns of ABC Requirements: By default, column A is the main sorting method. If columns A are the same, the same elements are sorted in column C in reverse order. Column B does not actually participate in sorting, but it is useful in practical applications, so it is also written. method one:

  1. $a = $c = array();
  2. foreach($list as $val){
  3. $a[] = $val[0]; //column a
  4. $c [] = $val[2]; //Column c
  5. }
  6. //Install column a in ascending order, and then install column b in descending order, similar to sql, orderby a asc,b desc
  7. array_multisort($a,SORT_ASC, $c, SORT_DESC , $list);
  8. print_r($list);
Copy code

Method 2:

  1. for($j=0;$j for($i=count($list)-1;$i>$j ;$i--){
  2. if($list[$i][0] == $list[$i-1][0] && $list[$i][2] > $list[$i- 1][2])
  3. list($list[$i],$list[$i-1]) = array($list[$i-1],$list[$i]);
  4. }
  5. }
Copy code


source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template