Pārlūkot izejas kodu

前端分类接口截取数量返回

Home 4 gadi atpakaļ
vecāks
revīzija
31fbbb1be7
2 mainītis faili ar 37 papildinājumiem un 2 dzēšanām
  1. 11 1
      app/api/controller/Category.php
  2. 26 1
      app/common/lib/Arr.php

+ 11 - 1
app/api/controller/Category.php

@@ -16,8 +16,18 @@ class Category extends ApiBase
     public function index()
     {
         // 获取所有分类的内容
-        $categorys = (new CategoryBusiness())->getNormalCategory();
+        try {
+            $categorys = (new CategoryBusiness())->getNormalCategory();
+        } catch (\Exception $e) {
+            // 日志
+            return show(config('status.success'), '内部异常', []);
+        }
+        if (!$categorys) {
+            return show(config('status.success'), '数据为空', []);
+        }
+
         $result = Arr::getTree($categorys);
+        $result = Arr::sliceTreeArr($result);
         return show(config('status.success'), $result);
     }
 }

+ 26 - 1
app/common/lib/Arr.php

@@ -1,4 +1,5 @@
 <?php
+declare(strict_types=1);
 
 namespace app\common\lib;
 
@@ -10,7 +11,7 @@ class Arr
      * @param $data
      * @return array
      */
-    public static function getTree($data): array
+    public static function getTree(array $data): array
     {
         $items = [];
         foreach ($data as $v) {
@@ -26,4 +27,28 @@ class Arr
         }
         return $tree;
     }
+
+    /**
+     * 对前端的分类数目进行截取
+     * @param array $data
+     * @param int $firstCount
+     * @param int $secondCount
+     * @param int $threeCount
+     * @return array
+     */
+    public static function sliceTreeArr(array $data, int $firstCount = 5, int $secondCount = 3, int $threeCount = 5): array
+    {
+        $data = array_slice($data, 0, $firstCount);
+        foreach ($data as $k => $v) {
+            if (!empty($v['list'])) {
+                $data[$k]['list'] = array_slice($v['list'], 0, $secondCount);
+                foreach ($v['list'] as $kk => $vv) {
+                    if (!empty($vv['list'])) {
+                        $data[$k]['list'][$kk]['list'] = array_slice($vv['list'], 0, $threeCount);
+                    }
+                }
+            }
+        }
+        return $data;
+    }
 }