seven 2 روز پیش
والد
کامیت
5b1a86cfc5
2فایلهای تغییر یافته به همراه36 افزوده شده و 1 حذف شده
  1. 34 0
      app/Services/BaseService.php
  2. 2 1
      app/Services/MenuService.php

+ 34 - 0
app/Services/BaseService.php

@@ -152,6 +152,40 @@ abstract class BaseService
         return $arr;
     }
 
+
+    public static function buildTree($list,$pid_name='pid',$id_name='id')
+    {
+        // 创建映射表
+        $map = [];
+        foreach ($list as $item) {
+            $map[$item[$id_name]] = $item;
+        }
+
+        // 找到顶级节点
+        $topLevelNodes = [];
+        foreach ($map as $key => $value) {
+            if (!isset($map[$value[$pid_name]])) {
+                $topLevelNodes[$key] = &$map[$key];
+            }
+        }
+
+        // 构建树形结构
+        $tree = [];
+        foreach ($map as &$item) {
+            if (isset($item[$pid_name]) && isset($map[$item[$pid_name]])) {
+                $parent = &$map[$item[$pid_name]];
+                if (!isset($parent['children'])) {
+                    $parent['children'] = [];
+                }
+                $parent['children'][] = &$item;
+            } else {
+                $tree[] = &$item;
+            }
+        }
+
+        return $tree;
+    }
+
     /**
      * @description: 实例化TG
      * @return {*}

+ 2 - 1
app/Services/MenuService.php

@@ -174,7 +174,8 @@ class MenuService extends BaseService
             $list = $allMenus;
         }
 
-        $tree = self::toTree($list,0,0,'parent_id');
+        // $tree = self::toTree($list,0,0,'parent_id');
+        $tree = self::buildTree($list,'parent_id');
         return $tree;
     }