Numeric index array:
BOOL Usort (array & $array, callback $cmp _function)
The Usort function sorts the specified array (parameter 1) by the specified method (parameter 2).
When we want to sort multidimensional arrays, each element of a multidimensional array is an array type, and how do two arrays compare size? This needs to be customized by the user (by comparing the first element of each array or ...).
Copy CodeThe code is as follows:
Defining multidimensional arrays
$a = Array (
Array ("Sky", "Blue"),
Array ("Apple", "Red"),
Array ("Tree", "green"));
A custom array comparison function, which is compared by the second element of the array.
function My_compare ($a, $b) {
if ($a [1] < $b [1])
return-1;
else if ($a [1] = = $b [1])
return 0;
Else
return 1;
}
Sort
Usort ($a, ' my_compare ');
Output results
foreach ($a as $elem) {
echo "$elem [0]: $elem [1]
";
}
?>
The result is:
Copy CodeThe code is as follows:
Sky:blue
Tree:green
Apple:red
Associative arrays:
BOOL Uasort (array & $array, callback $cmp _function)
BOOL Uksort (array & $array, callback $cmp _function)
Uasort, Uksort usage is the same as Usort, where Uasort () sorts the value of the associative array (value), and Uksort () sorts the keyword (key) of the associative array.
Copy CodeThe code is as follows:
$a = Array (
' Sunday ' = = Array (0, ' 7th '),
' Friday ' = = Array (5, ' 5th '),
' Tuesday ' = = Array (2, ' 2nd '));
function My_compare ($a, $b) {
if ($a [1] < $b [1])
return-1;
else if ($a [1] = = $b [1])
return 0;
Else
return 1;
}
Sort by the second element (7th,5th,2nd) of the value of the $ A array
Uasort ($a, ' my_compare ');
foreach ($a as $key = = $value) {
echo "$key: $value [0] $value [1]
";
}
Sort by the second character (r,u,u) of the keyword of the $ A array
Uksort ($a, ' my_compare ');
foreach ($a as $key = = $value) {
echo "$key: $value [0] $value [1]
";
}
?>
The result is:
Tuesday:2 2nd
Friday:5 5th
sunday:0 7th
Friday:5 5th
sunday:0 7th
Tuesday:2 2nd
http://www.bkjia.com/PHPjc/322116.html www.bkjia.com true http://www.bkjia.com/PHPjc/322116.html techarticle Numeric index array: bool Usort (array lt;?). PHP//define multidimensional Array $a = Array ("Sky", "Blue"), Array ("Apple", "red"), Array ("Tree", "green"); Custom array comparison functions, ...