Tác dụng của hàm array_multisort()
The array_multisort()
function sort multiple arrays at once, or a multi-dimensional array by one or more dimensions. The sorting is done as though the arrays were columns in a table.
Associative or string keys will be preserved, but numeric keys will be re-indexed.
The following table summarizes the technical details of this function.
Return Value: | Returns TRUE on success or FALSE on failure. |
---|---|
Changelog: |
The sort flags The sort flag
SORT_LOCALE_STRING was added in PHP 5.3.0 |
Version: | PHP 4+ |
Syntax
The basic syntax of the array_multisort()
function is given with:
The following example shows the array_multisort()
function in action.
Example
Run this code »<?php
// Sample arrays
$array1 = array(2, 7, 10, 5);
$array2 = array(4, 3, 1, 2);
// Sorting multiple arrays
array_multisort($array1, $array2);
print_r($array1);
print_r($array2);
?>
Tip: The first array is the main one to sort by; all items in the other arrays are reordered based on the sorted order of the first array (i.e., arrays are treated as columns of a table). If items in the first array compare as equal, the sort order is determined by the second array, and so on.
In the above example after sorting, the first array will contain 2, 5, 7, 10, the second array will contain 4, 2, 3, 1. Notice that the entries in the second array corresponds to the entries in the first array. To better understand this, let's take a closer look at the following illustration.
array1 | array2 --------+-------- 2 | 4 7 | 3 10 | 1 5 | 2 |
array1 | array2 --------+-------- 2 | 4 5 | 2 7 | 3 10 | 1 |
|
Before Sorting | After Sorting |
Parameters
The array_multisort()
function accepts the following parameters.
Parameter | Description |
---|---|
array1 | Required. Specifies the array to sort. |
array1_sort_order |
Optional. Specifies the sorting order. Possible values are:
|
array1_sort_flags |
Optional. Specifies how array items should be compared. Possible values are:
|
... | Optional. Specifies more arrays to sort, optionally followed by sort order and flags. Only elements corresponding to equivalent elements in previous arrays are compared. |
More Examples
Here're some more examples showing how array_multisort()
function basically works:
The following example shows how to sort a multi-dimensional array with this function.
Example
Run this code »<?php
// Sample array
$array = array(
array("10", 11, 100, 100, "a"),
array(1, 4, "2", 5, 3)
);
// Sorting multi-dimensional array
array_multisort($array[0], SORT_STRING, $array[1], SORT_DESC, SORT_NUMERIC);
print_r($array);
?>