Home >Backend Development >PHP Tutorial >php array_multisort multidimensional array sorting example
I estimate that the values of the two arrays are corresponding from beginning to end: 1 corresponds 6 and 9 correspond to 2, and 5 corresponds to 4. Let’s see what happens if we add one more array:
View the results. 1 corresponds to 6 and 3 from beginning to end, and the same is true for other items. This correspondence is what the manual calls "preserving the original key name association during sorting". Alternatively, you can 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 first sort by the first array (imagine as a column), and if the values in the first array (column) are the same, then sort by the second array (column). test:
You can imagine that the result of $arr3 here is (3,8,0,7). 2. Parameters of array_multisort. 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 this array_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, a sort type flag, or both flags at the same time. But only one sort flag of each type can appear after each array. Sort order flags: SORT_ASC - Sort in ascending order (default) SORT_DESC - Sort in descending order Sort type flag: SORT_REGULAR - compare items normally (default) SORT_NUMERIC - Compare items numerically SORT_STRING - Compare items by string 3. The actual function of array_multisort Usually there are some multidimensional arrays that need to be sorted:
For the usage of PHP array function array_multisort(), you can also read these articles: php array functions array_map, array_multisort multidimensional array sorting examples The difference between php array sorting function array_multisort and uasort php array function array_multisort() usage Usage examples of array_multisort() in php For example, if you want to sort by grades in descending order, if the grades are the same, sort by name in ascending order. At this time we need to create two more arrays according to the order of $guys: $scores = array(80,70,80,20);$names = array('jake','jin','john','ben ');Then array_multisort($scores, SORT_DESC, $names, $guys); That's it. Can it be more flexible? Do I have to get some additional arrays every time I want to sort? In fact, it is well encapsulated in the helper_array class of qeephp. Here are its two methods. You can make slight modifications when using it:
|