Use built-in functions to solve the PHP multi-dimensional array Sorting Problem

Source: Internet
Author: User

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:

 
 
  1. php 
  2. functioncmp($a,$b){  
  3. if($a[”nums”]==$b[”nums”]){  
  4. return0;  
  5. }  
  6. return($a[”nums”]<$b[”nums”])?-1:1;  
  7. }  
  8. $arr=Array(  
  9. 0=>Array(  
  10. “username”=>owen,  
  11. “nums”=>2,  
  12. ),  
  13. 1=>Array(  
  14. “username”=>d5s,  
  15. “nums”=>5,  
  16. ),  
  17. 2=>Array(  
  18. “username”=>pt,  
  19. “nums”=>3,  
  20. ),  
  21. );  
  22. uasort($arr,“cmp”);  
  23. echo‘<prestyleprestyle=”text-align:left”>’;  
  24. print_r($arr);  
  25. echo‘ pre>’;  
  26. ?> 
  27.  
  28. Array  
  29. (  
  30. [0]=>Array  
  31. (  
  32. [username]=>owen  
  33. [nums]=>2  
  34. )  
  35.  
  36. [2]=>Array  
  37. (  
  38. [username]=>pt  
  39. [nums]=>3  
  40. )  
  41.  
  42. [1]=>Array  
  43. (  
  44. [username]=>d5s  
  45. [nums]=>5  
  46. )  
  47.  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.