- $users = Array (
- Array (' name ' = ' Tom ', ' age ' = 20)
- , Array (' name ' = ' Anny ', ' age ' = 18)
- , Array (' name ' = ' Jack ', ' age ' = 22)
- );
Copy CodeI want to be able to sort by age from small to large. Method 1, use Array_multisort to extract the age to be stored in a one-dimensional array, and then in ascending order of age. Code:
- $ages = Array ();
- foreach ($users as $user) {
- $ages [] = $user [' Age '];
- }
- Array_multisort ($ages, SORT_ASC, $users);
Copy CodeAfter execution, $users is a sorted array and can be printed out to see. If you need to first sort by age, and then by name in ascending order, the same way, is to extract an array of names, the final sorting method to call:
- Array_multisort ($ages, SORT_ASC, $names, SORT_ASC, $users);
Copy CodeMethod 2, using Usort This method allows you to customize some of the more complex sorting methods. For example, sort by name in descending order of length:
- Usort ($users, function ($a, $b) {
- $al = strlen ($a [' name ']);
- $BL = strlen ($b [' name ']);
- if ($al = = $BL)
- return 0;
- Return ($al > $bl)? -1:1;
- });
Copy CodeAnonymous functions are used here and can be extracted separately if necessary. A $ A, $b can be understood as an element under the $users array, you can directly index the name value, calculate the length, and then compare the length. The second method is recommended because fewer steps are taken to extract the sorted content into a one-dimensional array, and the ordering method is more flexible. |