DataExtend.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace app\extra\tools;
  3. class DataExtend
  4. {
  5. /**
  6. * 一维数组转多维数据树
  7. * @param array $its 待处理数据
  8. * @param string $cid 自己的主键
  9. * @param string $pid 上级的主键
  10. * @param string $sub 子数组名称
  11. * @return array
  12. */
  13. public static function arr2tree(array $its, string $cid = 'id', string $pid = 'pid', string $sub = 'children'): array
  14. {
  15. [$tree, $its] = [[], array_column($its, null, $cid)];
  16. foreach ($its as $it) isset($its[$it[$pid]]) ? $its[$it[$pid]][$sub][] = &$its[$it[$cid]] : $tree[] = &$its[$it[$cid]];
  17. return $tree;
  18. }
  19. /**
  20. * 一维数组转数据树表
  21. * @param array $its 待处理数据
  22. * @param string $cid 自己的主键
  23. * @param string $pid 上级的主键
  24. * @param string $path 当前 PATH
  25. * @return array
  26. */
  27. public static function arr2table(array $its, string $cid = 'id', string $pid = 'pid', string $path = 'path'): array
  28. {
  29. $call = function (array $its, callable $call, array &$data = [], string $parent = '') use ($cid, $pid, $path) {
  30. foreach ($its as $it) {
  31. $ts = $it['sub'] ?? [];
  32. unset($it['sub']);
  33. $it[$path] = "{$parent}-{$it[$cid]}";
  34. $it['spc'] = count($ts);
  35. $it['spt'] = substr_count($parent, '-');
  36. $it['spl'] = str_repeat('ㅤ├ㅤ', $it['spt']);
  37. $it['sps'] = ",{$it[$cid]},";
  38. array_walk_recursive($ts, function ($val, $key) use ($cid, &$it) {
  39. if ($key === $cid) $it['sps'] .= "{$val},";
  40. });
  41. $it['spp'] = arr2str(str2arr(strtr($parent . $it['sps'], '-', ',')));
  42. $data[] = $it;
  43. if (empty($ts)) continue;
  44. $call($ts, $call, $data, $it[$path]);
  45. }
  46. return $data;
  47. };
  48. return $call(static::arr2tree($its, $cid, $pid), $call);
  49. }
  50. /**
  51. * 获取数据树子ID集合
  52. * @param array $list 数据列表
  53. * @param mixed $value 起始有效ID值
  54. * @param string $ckey 当前主键ID名称
  55. * @param string $pkey 上级主键ID名称
  56. * @return array
  57. */
  58. public static function getArrSubIds(array $list, $value = 0, string $ckey = 'id', string $pkey = 'pid'): array
  59. {
  60. $ids = [intval($value)];
  61. foreach ($list as $vo) if (intval($vo[$pkey]) > 0 && intval($vo[$pkey]) === intval($value)) {
  62. $ids = array_merge($ids, static::getArrSubIds($list, intval($vo[$ckey]), $ckey, $pkey));
  63. }
  64. return $ids;
  65. }
  66. }