Two methods for sorting two-dimensional arrays in PHP

WBOY
Release: 2016-07-25 09:11:05
Original
2455 people have browsed it
  1. $users = array(
  2. array('name' => 'tom', 'age' => 20)
  3. , array('name' => 'anny', 'age' => ; 18)
  4. , array('name' => 'jack', 'age' => 22)
  5. );
Copy code

Hope to sort by age from small to large.

The following are two methods compiled by me and shared with everyone for learning reference.

1. Use array_multisort

Using this method, it will be more troublesome. You need to extract the age and store it in a one-dimensional array, and then arrange it in ascending order by age. The specific code is as follows:

  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: array_multisort($ages, SORT_ASC, $names, SORT_ASC, $users);

2. Use usort

The biggest advantage of using this method is that you 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

Anonymous function is used here, if any It can also be extracted separately if needed. 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. It is recommended to use the second method, because there are fewer steps to extract the sorted content into a one-dimensional array, and the sorting method is more flexible.

>>> For more information, please view the complete list of php array sorting methods



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