To sort one-dimensional arrays, you can use asort, ksort, and other methods to sort processes, which is relatively simple. How can we sort two-dimensional arrays? Use array_multisort and usort to implement the following array:
The code is as follows:
$ 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. I have sorted out two methods and shared them with you.
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:
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 want 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:
The code is 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:
The code is as follows:
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.
I prefer the second method, because the steps for extracting the Sorted content to one-dimensional arrays are missing, and the sorting method is more flexible.