Home >Backend Development >PHP Tutorial >alwayscomebacktoyourlove PHP multidimensional array sorting usort,uasort
Numeric index array:
bool usort( array &$array, callback $cmp_function )
usort function sorts the specified array (parameter 1) in the specified way (parameter 2).
When we want to sort a multi-dimensional array, each element of the multi-dimensional array is an array type, and how do we compare the sizes of the two arrays? This needs to be customized by the user (whether to compare based on the first element of each array or...).
Copy the code The code is as follows:
//Define multi-dimensional array
$a = array(
array("sky", "blue"),
array("apple", " red"),
array("tree", "green"));
//Customized array comparison function, compare based on 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]
";
}
?>
Copy the code The code is as follows:
sky : blue
tree : green
apple : red
Copy code The 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;
}
//Press the second element of the value of the $a array (7th ,5th,2nd) to sort
uasort($a, 'my_compare');
foreach($a as $key => $value) {
echo "$key : $value[0] $value[1]< ;br />";
}
//Sort by the second character (r, u, u) of the key of the $a array
uksort($a, 'my_compare');
foreach($a as $key => $value) {
echo "$key : $value[0] $value[1]
";
}
?>
The above has introduced alwayscomebacktoyourlove PHP multi-dimensional array sorting usort and uasort, including the content of alwayscomebacktoyourlove. I hope it will be helpful to friends who are interested in PHP tutorials.