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:
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:
Method 2, use usort This method can customize some more complex sorting methods. For example, sort in descending order by name length:
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. |