- $ Users = array (
- Array ('name' => 'Tom ', 'age' => 20)
- , Array ('name' => 'anny ', 'age' => 18)
- , Array ('name' => 'Jack', 'age' => 22)
- );
We hope to sort data by age size from small to large. The following two methods are provided for your reference. 1. use array_multisort Using this method will be more troublesome. you need to extract the age and store it in a one-dimensional array, and then sort it in ascending order by age. The code is as follows:
- $ Ages = array ();
- Foreach ($ users as $ user ){
- $ Ages [] = $ user ['age'];
- }
-
- Array_multisort ($ ages, SORT_ASC, $ users );
After Execution, $ users is the sorted array. you can print it out. If you need to sort by age in ascending order and then by name in ascending order, the method is the same as above, that is, to extract an array of names, the final sorting method is called as follows: 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 complicated sorting methods. For example, sort by name length in descending order:
- Usort ($ users, function ($ a, $ B ){
- $ Al = strlen ($ a ['name']);
- $ Bl = strlen ($ B ['name']);
- If ($ al = $ bl)
- Return 0;
- Return ($ al> $ bl )? -1: 1;
- });
The anonymous function is used here. if necessary, it can be extracted separately. $ A and $ B can be understood as elements in the $ users array. you can directly index the name value, calculate the length, and then compare the length. We recommend that you use the second method because the steps for extracting the Sorted content to one-dimensional arrays are missing and the sorting method is more flexible. >>> For more information, see The php array sorting method < |