使用usort和自定义比较函数的多维数组/对象排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用usort和自定义比较函数的多维数组/对象排序相关的知识,希望对你有一定的参考价值。

  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. ?>

以上是关于使用usort和自定义比较函数的多维数组/对象排序的主要内容,如果未能解决你的问题,请参考以下文章

usort() 自定义排序

使用 PHP usort() 通过用户自定义的比较函数对数组进行排序

PHP多维数组的排序问题

通过继续值对Usort排序多维数组

sort方法和自定义比较器的写法

关于回调函数 usort() uksrot() sort() 介绍简介实验是从小到大排序