Home  >  Article  >  Backend Development  >  PHP two-dimensional array sorting method (array_multisort usort function)

PHP two-dimensional array sorting method (array_multisort usort function)

WBOY
WBOYOriginal
2016-07-25 08:55:101176browse
  1. $users = array(
  2. array('name' => 'tom', 'age' => 20)
  3. , array('name' => 'anny', 'age' => ; 18)
  4. , array('name' => 'jack', 'age' => 22)
  5. );
Copy the code

I hope to sort by age from small to large.

Method 1. Use array_multisort To extract age, store it in a one-dimensional array, and then sort it in ascending order by age. Code:

  1. $ages = array();
  2. foreach ($users as $user) {
  3. $ages[] = $user['age'];
  4. }
  5. array_multisort($ages, SORT_ASC, $users);
Copy the code

After execution, $users will be a sorted array, which can be printed out to see. If you need to sort by age in ascending order first, and then by name in ascending order, the method is the same as above, which is to extract an additional name array. The final sorting method is called like this:

  1. array_multisort($ages, SORT_ASC, $names, SORT_ASC, $users);
Copy code

Method 2, use usort This method can customize some more complex sorting methods.

For example, sort in descending order by name length:

  1. usort($users, function($a, $b) {
  2. $al = strlen($a['name']);
  3. $bl = strlen($b[' name']);
  4. if ($al == $bl)
  5. return 0;
  6. return ($al > $bl) ? -1 : 1;
  7. });
Copy code

Use here An anonymous function can be extracted separately if necessary. Among them, $a and $b can be understood as elements under the $users array. You can directly index the name value, calculate the length, and then compare the lengths.

The second method is recommended because it eliminates the step of extracting the sorted content into a one-dimensional array, and the sorting method is more flexible.



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