PHP multidimensional array sorting example

WBOY
Release: 2016-07-25 09:07:27
Original
805 people have browsed it
  1. $array = array(

  2. '0' => array('3', 'one'),
  3. '1' => array('101' , 'two'),
  4. '2' => array('12', 'three'),
  5. '3' => array('13', 'four'),
  6. '4' => array ('1', 'five'),
  7. '5' => array('3', 'six'),
  8. );

  9. /*Method 1: Using uasort () function instead of usort() function. The difference is that uasort() will maintain the original index and usort() will rebuild the index. */

  10. function cmp($a, $b){
  11. if($a[0] == $b[0]){
  12. return 0;
  13. }
  14. return($a[0] < $b[0 ]) ? -1 : 1;
  15. }

  16. uasort($array,"cmp");

  17. print_r($array);

  18. echo "
    **********************
    ";

  19. /*Method 2: Use array_multisort*/

  20. foreach ($array as $key=>$value){
  21. $first[$key] = $value[0];
  22. $second[$key] = $value[1];
  23. }
  24. array_multisort($first,SORT_NUMERIC,SORT_ASC,$second,SORT_STRING,SORT_ASC,$array);
  25. print_r($array);
  26. /*
  27. Sort order flag:
  28. SORT_ASC – as per Sort in ascending order
  29. SORT_DESC - Sort in descending order

  30. Sort type flags:

  31. SORT_REGULAR - Compare items in the usual way
  32. SORT_NUMERIC - Compare items in numerical order
  33. SORT_STRING - Compare items in strings
  34. */

Copy code

>>> For more information, please view the complete list of php array sorting methods



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 admin@php.cn
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!