作者 何书鹏
1 个管道 的构建 通过 耗费 1 秒

完善代码

@@ -37,9 +37,9 @@ class Category extends Api @@ -37,9 +37,9 @@ class Category extends Api
37 foreach($list as $v){ 37 foreach($list as $v){
38 $v->visible(['id','pid','name','image']); 38 $v->visible(['id','pid','name','image']);
39 } 39 }
40 - $tree = Tree::instance();  
41 - $tree->init(collection($list)->toArray(), 'pid');  
42 - $list = $this->getTreeList($tree->getTreeArray(0)); 40 + $this->tree = Tree::instance();
  41 + $this->tree->init(collection($list)->toArray(), 'pid');
  42 + $list = $this->getTreeArray(0);
43 // 拼接全部一级分类,方便前端展示 43 // 拼接全部一级分类,方便前端展示
44 $all_list = []; 44 $all_list = [];
45 foreach($list as $v){ 45 foreach($list as $v){
@@ -51,18 +51,12 @@ class Category extends Api @@ -51,18 +51,12 @@ class Category extends Api
51 "pid" => 0, 51 "pid" => 0,
52 "name" => "全部", 52 "name" => "全部",
53 "image" => cdnurl('/assets/img/qrcode.png',true), 53 "image" => cdnurl('/assets/img/qrcode.png',true),
54 - "type_text" => "商品分类",  
55 - "flag_text" => "",  
56 - "spacer" => "",  
57 "childlist" => [ 54 "childlist" => [
58 [ 55 [
59 "id" => 0, 56 "id" => 0,
60 "pid" => 0, 57 "pid" => 0,
61 "name" => "全部", 58 "name" => "全部",
62 "image" => cdnurl('/assets/img/qrcode.png',true), 59 "image" => cdnurl('/assets/img/qrcode.png',true),
63 - "type_text" => "商品分类",  
64 - "flag_text" => "",  
65 - "spacer" => "",  
66 "childlist" => $all_list 60 "childlist" => $all_list
67 ] 61 ]
68 ], 62 ],
@@ -103,21 +97,29 @@ class Category extends Api @@ -103,21 +97,29 @@ class Category extends Api
103 $this->success(__('成功'),compact('list')); 97 $this->success(__('成功'),compact('list'));
104 } 98 }
105 99
106 - // 判断等级和是否有下级  
107 - private function getTreeList($data = [], $level = 1) 100 + /**
  101 + *
  102 + * 获取树状数组
  103 + * @param string $myid 要查询的ID
  104 + * @return array
  105 + */
  106 + private function getTreeArray($myid, $level = 1)
108 { 107 {
109 - $arr = []; 108 + $childs = $this->tree->getChild($myid);
110 $n = 0; 109 $n = 0;
111 - foreach ($data as $k => $v) {  
112 - $childlist = isset($v['childlist']) ? $v['childlist'] : [];  
113 - $v['haschild'] = $childlist ? 1 : 0;  
114 - $v['level'] = $v['pid'] == 0 ? 1 : $level+1;  
115 - $arr[$n] = $v;  
116 - if ($childlist) {  
117 - $arr[$n]['childlist'] = $this->getTreeList($childlist, $v['level']); 110 + $data = [];
  111 + if ($childs) {
  112 + foreach ($childs as $id => $value) {
  113 + unset($value['type_text']);
  114 + unset($value['flag_text']);
  115 + $data[$n] = $value;
  116 + $level_plus = $value['pid'] == 0 ? 1 : $level+1;
  117 + $data[$n]['childlist'] = $this->getTreeArray($id, $level_plus);
  118 + $data[$n]['haschild'] = !empty($data[$n]['childlist']) ? 1 : 0;
  119 + $data[$n]['level'] = $level_plus;
  120 + $n++;
118 } 121 }
119 - $n++;  
120 } 122 }
121 - return $arr; 123 + return $data;
122 } 124 }
123 } 125 }