Detailed explanation of how PHP uses usort and uasort functions to implement multi-dimensional array sorting

伊谢尔伦
Release: 2023-03-11 13:58:02
Original
1996 people have browsed it

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...).

"; 
} 

?>
Copy after login

The result is:

sky : blue 
tree : green 
apple : red
Copy after login

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.

 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]
"; } //按$a数组的关键字的第二个字符(r,u,u)进行排序 uksort($a, 'my_compare'); foreach($a as $key => $value) { echo "$key : $value[0] $value[1]
"; } ?>
Copy after login

The result is:

Tuesday : 2 2nd 
Friday : 5 5th 
Sunday : 0 7th 
Friday : 5 5th 
Sunday : 0 7th 
Tuesday : 2 2nd
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!