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:
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:
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 |