Sort () Sorts the indexed array in ascending order, whose inverse function is Rsort ()
Asort () Sorts the values of the associative array in ascending order, whose inverse function is Arsort ()
Ksort () Sorts the key names of the associative array in ascending order, whose inverse function is Krsort ()
Usort () Sorts multidimensional arrays (with Uasort () and Uksort () functions, as in the usage)
Definition and usage
The Usort () function uses a user-defined function to sort the array.
Note: If two elements compare the same result, their order in the sorted array is undefined. Before PHP 4.0.6, the user-defined function retains the original order of these elements. However, because of the introduction of a new sorting algorithm in 4.1.0, the result will not be this, because there is no effective solution to this.
Note: This function assigns the new key name to the element in the array . This will delete the original key name.
Grammar
Usort (Array,sorttype)
Parameters |
Description |
Array |
Necessary. Specifies the array to sort. |
function |
Necessary. User-defined functions. The function must be designed to return 1, 0, or 1, and should accept two parameters for comparison and work in a manner similar to the following:
- If a = B, returns 0
- If a > B, return 1
- If a < B, return-1
|
Example
<?phpfunction my_sort ($a, $b) { if ($a = = $b) return 0; return ($a > $b)? -1:1; } $arr = Array ("Peter", "Glenn", "Cleveland", "Peter", "Cleveland", "Glenn"), Usort ($arr, "My_sort");p Rint_r ($arr); >
Output:
Array ([0] = peter[1] = glenn[2] = cleveland[3] = peter[4] = glenn[5] = Cleveland)
Example 2
function compare ($a, $b) {
if ($a [1]== $b [1]) {
return 0;
}elseif ($a [1]> $b [1]) {
return 1;
}else{
return-1;
}
}
$arr =array (
Array ("DF", 123),
Array ("AA", 333),
Array ("GG", 222)
);
Print_r ($arr);
echo "<br>";
Usort ($arr, ' compare ');
Print_r ($arr);
PHP array sorting