Arr.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\common\lib;
  4. class Arr
  5. {
  6. /**
  7. * 分类树,支持无限极分类
  8. * @param $data
  9. * @return array
  10. */
  11. public static function getTree(array $data): array
  12. {
  13. $items = [];
  14. foreach ($data as $v) {
  15. $items[$v['id']] = $v;
  16. }
  17. $tree = [];
  18. foreach ($items as $id => $item) {
  19. if (isset($items[$item['pid']])) {
  20. $items[$item['pid']]['list'][] = &$items[$id];
  21. } else {
  22. $tree[] = &$items[$id];
  23. }
  24. }
  25. return $tree;
  26. }
  27. /**
  28. * 对前端的分类数目进行截取
  29. * @param array $data
  30. * @param int $firstCount
  31. * @param int $secondCount
  32. * @param int $threeCount
  33. * @return array
  34. */
  35. public static function sliceTreeArr(array $data, int $firstCount = 5, int $secondCount = 3, int $threeCount = 5): array
  36. {
  37. $data = array_slice($data, 0, $firstCount);
  38. foreach ($data as $k => $v) {
  39. if (!empty($v['list'])) {
  40. $data[$k]['list'] = array_slice($v['list'], 0, $secondCount);
  41. foreach ($v['list'] as $kk => $vv) {
  42. if (!empty($vv['list'])) {
  43. $data[$k]['list'][$kk]['list'] = array_slice($vv['list'], 0, $threeCount);
  44. }
  45. }
  46. }
  47. }
  48. return $data;
  49. }
  50. }