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

完善代码

... ... @@ -37,9 +37,9 @@ class Category extends Api
foreach($list as $v){
$v->visible(['id','pid','name','image']);
}
$tree = Tree::instance();
$tree->init(collection($list)->toArray(), 'pid');
$list = $this->getTreeList($tree->getTreeArray(0));
$this->tree = Tree::instance();
$this->tree->init(collection($list)->toArray(), 'pid');
$list = $this->getTreeArray(0);
// 拼接全部一级分类,方便前端展示
$all_list = [];
foreach($list as $v){
... ... @@ -51,18 +51,12 @@ class Category extends Api
"pid" => 0,
"name" => "全部",
"image" => cdnurl('/assets/img/qrcode.png',true),
"type_text" => "商品分类",
"flag_text" => "",
"spacer" => "",
"childlist" => [
[
"id" => 0,
"pid" => 0,
"name" => "全部",
"image" => cdnurl('/assets/img/qrcode.png',true),
"type_text" => "商品分类",
"flag_text" => "",
"spacer" => "",
"childlist" => $all_list
]
],
... ... @@ -103,21 +97,29 @@ class Category extends Api
$this->success(__('成功'),compact('list'));
}
// 判断等级和是否有下级
private function getTreeList($data = [], $level = 1)
/**
*
* 获取树状数组
* @param string $myid 要查询的ID
* @return array
*/
private function getTreeArray($myid, $level = 1)
{
$arr = [];
$childs = $this->tree->getChild($myid);
$n = 0;
foreach ($data as $k => $v) {
$childlist = isset($v['childlist']) ? $v['childlist'] : [];
$v['haschild'] = $childlist ? 1 : 0;
$v['level'] = $v['pid'] == 0 ? 1 : $level+1;
$arr[$n] = $v;
if ($childlist) {
$arr[$n]['childlist'] = $this->getTreeList($childlist, $v['level']);
$data = [];
if ($childs) {
foreach ($childs as $id => $value) {
unset($value['type_text']);
unset($value['flag_text']);
$data[$n] = $value;
$level_plus = $value['pid'] == 0 ? 1 : $level+1;
$data[$n]['childlist'] = $this->getTreeArray($id, $level_plus);
$data[$n]['haschild'] = !empty($data[$n]['childlist']) ? 1 : 0;
$data[$n]['level'] = $level_plus;
$n++;
}
$n++;
}
return $arr;
return $data;
}
}
... ...