PHP数组递归排序实现方法示例

这篇文章主要介绍了PHP数组递归排序实现方法,结合实例形式分析了php基于递归算法针对特定key对数组进行排序的相关操作技巧,需要的朋友可以参考下。

本文实例讲述了PHP数组递归排序实现方法,分享给大家供大家参考,具体如下:

  1. /**
  2. * 递归根据特定key对数组排序
  3. * @param $data
  4. * @param string $orderKey
  5. * @param string $sonKey
  6. * @param int $orderBy
  7. * @return mixed
  8. */
  9. function recursion_orderby($data, $orderKey = 'order', $sonKey = 'children', $orderBy = SORT_ASC)
  10. {
  11. $func = function ($value) use ($sonKey, $orderKey, $orderBy) {
  12. if (isset($value[$sonKey]) && is_array($value[$sonKey])) {
  13. $value[$sonKey] = recursion_orderby($value[$sonKey], $orderKey, $sonKey, $orderBy);
  14. }
  15. return $value;
  16. };
  17. return array_orderby(array_map($func, $data), $orderKey, $orderBy);
  18. }
  19. $a = [
  20. [
  21. 'order' => 0,
  22. ],
  23. [
  24. 'order' => -1,
  25. 'children' => [
  26. [
  27. 'order' => 0,
  28. ],
  29. [
  30. 'order' => -2,
  31. 'children' => [
  32. ['order' => 0],
  33. ['order' => -1],
  34. ['order' => 1],
  35. ],
  36. ],
  37. ],
  38. ],
  39. [
  40. 'order' => 2,
  41. ],
  42. ];
  43. var_dump(recursion_orderby($a));
  44. /**
  45. * 输出:
  46. array(3) {
  47. [0] =>
  48. array(2) {
  49. 'order' =>
  50. int(-1)
  51. 'children' =>
  52. array(2) {
  53. [0] =>
  54. array(2) {
  55. 'order' =>
  56. int(-2)
  57. 'children' =>
  58. array(3) {
  59. [0] =>
  60. array(1) {
  61. 'order' =>
  62. int(-1)
  63. }
  64. [1] =>
  65. array(1) {
  66. 'order' =>
  67. int(0)
  68. }
  69. [2] =>
  70. array(1) {
  71. 'order' =>
  72. int(1)
  73. }
  74. }
  75. }
  76. [1] =>
  77. array(1) {
  78. 'order' =>
  79. int(0)
  80. }
  81. }
  82. }
  83. [1] =>
  84. array(1) {
  85. 'order' =>
  86. int(0)
  87. }
  88. [2] =>
  89. array(1) {
  90. 'order' =>
  91. int(2)
  92. }
  93. }
  94. */