When learning PHP, you may encounter the PHP multi-dimensional array Sorting Problem. Here we will introduce the solution to the PHP multi-dimensional array Sorting Problem. Here we will share it with you, hoping to help you.
Compare the size and sorting according to the keys of the array. php has many built-in functions, including krsort () and ksort () and so on. If the value is not repeated, You can first use array_flip () to exchange the key and value; then krsort (), and then switch back in array_flip () to compare the size. When there are duplicate values, we need to use some sorting algorithms. However, php's convenient callback function uasort () will keep the original index, and usort () will rebuild the index. PHP multi-dimensional array Sorting code:
- php
- functioncmp($a,$b){
- if($a[”nums”]==$b[”nums”]){
- return0;
- }
- return($a[”nums”]<$b[”nums”])?-1:1;
- }
- $arr=Array(
- 0=>Array(
- “username”=>owen,
- “nums”=>2,
- ),
- 1=>Array(
- “username”=>d5s,
- “nums”=>5,
- ),
- 2=>Array(
- “username”=>pt,
- “nums”=>3,
- ),
- );
- uasort($arr,“cmp”);
- echo‘<prestyleprestyle=”text-align:left”>’;
- print_r($arr);
- echo‘ pre>’;
- ?>
-
- Array
- (
- [0]=>Array
- (
- [username]=>owen
- [nums]=>2
- )
-
- [2]=>Array
- (
- [username]=>pt
- [nums]=>3
- )
-
- [1]=>Array
- (
- [username]=>d5s
- [nums]=>5
- )
-
- )