Use php to sort two-dimensional arrays by array values-php Tutorial

Source: Internet
Author: User
Sort two-dimensional arrays by array values using php
Multi-dimensional array sorting function code

  1. /**
  2. * Multi-dimensional array sorting
  3. * @ Param array $ array the array to be sorted
  4. * @ Param string $ sort by field of key
  5. * @ Param string $ order sorting method. 0 indicates descending order, and 1 indicates ascending order.
  6. */
  7. Function array_sort (array $ array, $ key, $ order = 1 ){
  8. $ Sort = [];
  9. // The correspondence between field values and key names is formed here
  10. Foreach ($ array as $ k => $ v ){
  11. $ Sort [$ v [$ key] = isset ($ sort [$ v [$ key])? Array_merge ($ sort [$ v [$ key], [$ k]): [$ k];
  12. }
  13. If ($ order = 1 & ksort ($ sort )){
  14. // Sort in ascending order
  15. } Elseif ($ order = 0 & krsort ($ sort )){
  16. } Else {
  17. Return false;
  18. }
  19. $ Rs = [];
  20. // Generate a new array based on the sorted relationship
  21. Foreach ($ sort as $ value ){
  22. Foreach ($ value as $ n ){
  23. $ Rs [] = $ array [$ n];
  24. }
  25. }
  26. Unset ($ sort, $ array );
  27. Return $ rs;
  28. }

Php

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.