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 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]
";
}
? >
The result is:
Copy the code The code is as follows:
sky : blue
tree : green
apple : red
Associative array:
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 values of the associative array, and uksort() sorts the keys of the associative array.
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) Sort
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 key 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.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322116.htmlTechArticleNumeric index array: bool usort( array lt;?php //Define multi-dimensional array $a = array( array( "sky", "blue"), array("apple", "red"), array("tree", "green")); //Customized array comparison function,...