When we want to sort multidimensional arrays, each element of the multidimensional 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...).
NumberIndexArray:
bool usort(array &$array, callback $cmp_function)
usort function operates on the specified array (parameter 1) in the specified way (parameter 2) Sort.
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...).
<?php //定义多维数组 $a = array( array("sky", "blue"), array("apple", "red"), array("tree", "green")); //自定义数组比较函数,按数组的第二个元素进行比较。 function my_compare($a, $b) { if ($a[1] < $b[1]) return -1; else if ($a[1] == $b[1]) return 0; else return 1; } //排序 usort($a, 'my_compare'); //输出结果 foreach($a as $elem) { echo "$elem[0] : $elem[1]<br />"; } ?>
The result is:
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, uksort() Sort the associative array by key.
<?php $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; } //按$a数组的值的第二个元素(7th,5th,2nd)进行排序 uasort($a, 'my_compare'); foreach($a as $key => $value) { echo "$key : $value[0] $value[1]<br />"; } //按$a数组的关键字的第二个字符(r,u,u)进行排序 uksort($a, 'my_compare'); foreach($a as $key => $value) { echo "$key : $value[0] $value[1]<br />"; } ?>
The result is:
Tuesday : 2 2nd Friday : 5 5th Sunday : 0 7th Friday : 5 5th Sunday : 0 7th Tuesday : 2 2nd
The above is the detailed content of Detailed explanation of how PHP uses usort and uasort functions to implement multi-dimensional array sorting. For more information, please follow other related articles on the PHP Chinese website!