Multi-Dimensional Array/Object Sort using usort and custom comparison function


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. /**
  4.  *
  5.  * EXAMPLE #1
  6.  *
  7.  * sort array of objects based on specified attribute values
  8.  * in this case "lastname", followed by "firstname"
  9.  *
  10.  **/
  11.  
  12. $person1 = (object) array('lastname' => 'Jones', 'firstname' => 'Michael', 'Degree' => 'AAA');
  13. $person2 = (object) array('lastname' => 'Adams', 'firstname' => 'Zach', 'Degree' => 'BB');
  14. $person3 = (object) array('lastname' => 'Smith', 'firstname' => 'Jim', 'Degree' => 'CCC');
  15. $person4 = (object) array('lastname' => 'Adams', 'firstname' => 'Tom', 'Degree' => 'DD');
  16.  
  17. $array_to_be_sorted = array( $person1, $person2, $person3, $person4);
  18.  
  19. echo "Before";
  20. echo "<pre>";
  21. print_r($array_to_be_sorted);
  22. echo "</pre>";
  23. echo "<br /><br />";
  24.  
  25. function alpha_sort($a, $b) {
  26.  
  27. if ($a->lastname == $b->lastname) {
  28. return strnatcmp($a->firstname, $b->firstname);
  29. }
  30. return strnatcmp($a->lastname, $b->lastname);
  31. }
  32.  
  33. usort($array_to_be_sorted, "alpha_sort");
  34.  
  35. echo "After";
  36. echo "<pre>";
  37. print_r($array_to_be_sorted);
  38. echo "</pre>";
  39.  
  40. ?>
  41.  
  42. <?php
  43.  
  44. /**
  45.  *
  46.  * EXAMPLE #2
  47.  *
  48.  * sort array of arrays based on specified array keys
  49.  * in this case "lastname", followed by "firstname"
  50.  *
  51.  **/
  52.  
  53.  
  54. $array_to_be_sorted = array(
  55. array('lastname' => 'Jones', 'firstname' => 'Michael'),
  56. array('lastname' => 'Adams', 'firstname' => 'Zach'),
  57. array('lastname' => 'Smith', 'firstname' => 'Jim'),
  58. array('lastname' => 'Adams', 'firstname' => 'Tom')
  59. );
  60.  
  61. function alpha_sort($a, $b) {
  62.  
  63. if ($a['lastname'] == $b['lastname']) {
  64. return strnatcmp($a['firstname'], $b['firstname']);
  65. }
  66. return strnatcmp($a['lastname'], $b['lastname']);
  67. }
  68.  
  69. usort($array_to_be_sorted, "alpha_sort");
  70.  
  71. echo "<pre>";
  72. print_r($array_to_be_sorted);
  73. echo "</pre>";
  74.  
  75. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.