thinkphp5无限极分类、递归、封装

浏览1197

像淘宝、京东等大型商城,都会用到无限极分类。

1501350840310487.png

效果图:

1501350428606368.png

数据表设计:

1501350428606368.png

PHP代码:

<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function index()
    {
        $list= \think\Db::name('cat')->order('id desc')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    public function add()
    {
        if(request()->isPost()){
            $pid=input('pid');
            $pre= \think\Db::name('cat')->where('id','=',$pid)->find();
            if($pre){
                $_POST['level']=$pre['level']+1;
            }else{
                $_POST['level']=1;
            }
            $data=[
                'name'=>input('name'),
                'pid'=>input('pid'),
                'level'=>$_POST['level'],
            ];
            $re= \think\Db::name('cat')->insert($data);
            if($re){
                return $this->success('添加成功','index/Index/index');
            }else{
                return $this->error('添加失败');
            }
        }else{
            $show="";
            $show=$this->getcalist();
           
        
        $this->assign('show',$show);
        return $this->fetch();
        
        
        }
        
    }
    public function getcalist($pid=0){
        $str="";
        
        $re= \think\Db::name('cat')->where('pid','=',$pid)->select();
        if($re){
            foreach($re as $k=>$r){
            $str.='<option value="'.$r['id'].'">'.$this->getspace($r['level']).$r['name'].'</option>';
                $str.=$this->getcalist($r['id']);
            }
        }
        return $str;
    }
    public function getspace($n){
        $str="";
        for($i=1;$i<$n;$i++){
            $str.="&nbsp;&nbsp;";
        }
        if($n==1){
            return $str;
        }else{
            return $str.'|-';
        }
        
    }
}

模板:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>分类添加</title>
</head>
<body>
<form action="" method="post">
<label>分类名称:</label>
<input type="text" name="name"/><br/>
<label>所属分类:</label>
<select name="pid">
    <option value="0">一级分类</option>
    {$show}
</select>
<br/><input type="submit" name="submit" value="提交"/>
</form>
</body>
</html>



  • 暂无任何回答