|
array_multisortSort multiple or multi-dimensional arrays Description
bool array_multisort
( array
&$array1
[, mixed $array1_sort_order = SORT_ASC
[, mixed $array1_sort_flags = SORT_REGULAR
[, mixed $...
]]] )array_multisort can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.
Parameters
Return Values
Returns Changelog
Examples
Example #1 Sorting multiple arrays
<?php In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well. array(4) { [0]=> int(0) [1]=> int(10) [2]=> int(100) [3]=> int(100) } array(4) { [0]=> int(4) [1]=> int(1) [2]=> int(2) [3]=> int(3) }
Example #2 Sorting multi-dimensional array
<?php In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order). array(2) { [0]=> array(5) { [0]=> string(2) "10" [1]=> int(100) [2]=> int(100) [3]=> int(11) [4]=> string(1) "a" } [1]=> array(5) { [0]=> int(1) [1]=> int(3) [2]=> string(1) "2" [3]=> int(2) [4]=> int(1) } }
Example #3 Sorting database results For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records. Example data: volume | edition -------+-------- 67 | 2 86 | 1 85 | 6 98 | 2 86 | 6 67 | 7 The data as an array, called data. This would usually, for example, be obtained by looping with mysqli_fetch_assoc.
<?php In this example, we will order by volume descending, edition ascending. We have an array of rows, but array_multisort requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.
<?php The dataset is now sorted, and will look like this: volume | edition -------+-------- 98 | 2 86 | 1 86 | 6 85 | 6 67 | 2 67 | 7
Example #4 Case insensitive sorting
Both To perform a case insensitive sort, force the sorting order to be determined by a lowercase copy of the original array.
<?php The above example will output: Array ( [0] => Alpha [1] => atomic [2] => bank [3] => Beta ) |