Home >Backend Development >PHP Tutorial >Use array mutisort to sort data by a certain field_PHP tutorial
Usage of array_multisort
1. Let’s look at the simplest case first. There are two arrays:
$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
array_multisort($arr1,$ arr2);
print_r($arr1); // The order obtained is 1,5,9
print_r($arr2); // The order obtained is 6,4,2
I estimate two The values of the array are corresponding from beginning to end: 1 corresponds to 6, 9 corresponds to 2, and 5 corresponds to 4.
Let’s add one more array and see what happens:
$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
$arr3 = array(3,7,8);
array_multisort($arr1,$arr2,$arr3);
Looking at the results, 1 corresponds to 6 and 3 from beginning to end, as well as other items in this way. This correspondence is what the manual calls "preserving the original key name association during sorting".
Also, you can also think of each array as a column in a database table. The corresponding 1,6,3 are one data row, and 9,2,7 are another data row. . .
array_multisort will sort by the first array (imagine as a column) first, and if the values of the first array (column) are the same, it will be sorted by the second array (column).
You can use the following program to test:
$arr1 = array(1,9,5,9);
$arr2 = array(6,2,4,1 );
$arr3 = array(3,7,8,0);
array_multisort($arr1,$arr2,$arr3);
You can imagine that the result of $arr3 here is (3,8, 0,7).
2. Next, we will explain the parameters of array_multisort.
The parameters of this function are very flexible. The simplest case is to use 1 or n arrays as parameters as shown above. It should be noted that the number of items in each array must be the same, otherwise a warning will cause the sorting to fail.
Like thisarray_multisort($arr1,$arr2,$arr3); By default, all arrays are arranged in ascending order. If you want to sort $arr2 in descending order and compare it as a string, you must write :
array_multisort($arr1, $arr2, SORT_DESC, SORT_STRING, $arr3);
Each array can be followed by a sort order flag or a sort type flag, or both flags at the same time Appear. But only one sort flag of each type can appear after each array.
Details are as follows:
Sort order flags:
SORT_ASC - Sort in ascending order (default)
SORT_DESC - Sort in descending order
Sort type flags:
SORT_REGULAR - Compare items according to the usual method (default)
SORT_NUMERIC - Compare items according to numeric values
SORT_STRING - Compare items according to strings
Actual effect: After extracting the data from the database, it may be an array. If you want to arrange it according to that field, you can extract that field first and become a separate array. , and then use array_multisort to sort the original data by a certain field. The following is a small example to sort the children by their scores.