数据表设计:
CREATE TABLE NewTable (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
pid int(10) UNSIGNED ZEROFILL NOT NULL ,
name varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
path varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
PRIMARY KEY (id)
)
ENGINE=MyISAM
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=53
CHECKSUM=0
ROW_FORMAT=DYNAMIC
DELAY_KEY_WRITE=0
;

前端页面





Document


四个字段的无限分类



请选择上级分类:
请填写分类的名称:



控制器
namespace app\index\controller;
use think\Db;
use think\Controller;
use app\model\Category;

class Index extends Controller
{
public function index()
{
//添加分类的界面
//查询所有的分类
$db=Db::name('categroy');
$data=$db->order('concat(path,"-",id)')->select();
#order('concat(path,"-",id)')自动排序
foreach ($data as &$cate) {
$prefix='';
$i=count(explode("-", $cate['path']));
for($n=0;$n<=$i;$n++){
$prefix.="--";
}
$cate['pre']=$prefix;
}
$this->assign('cates',$data);
return $this->fetch();
}
public function add(){
$db=Db::name('categroy');
if($_POST['pid']==0){
$_POST['path']=0;

    }else{
        $_POST['path']=$db->where('id='.$_POST['pid'])->value('path')."-".$_POST['pid'];   
    }
        $name=$_POST['name'];
    if($db->insert($_POST)){
        $this->success('添加成功');
    }else{
        $this->error('添加失败');
    }
   #原理:4个字段
   /*
   ID   PID   NAME   PATH
   1    0     服装    0-1
   2    0     游戏    0-2
   3    1     男装    0-1-3
   4    3     上衣    0-1-3-4
    */
}}

无线递归分类
public function user(){
$db=Db::name('categroy1');
// $data=$db->getTree();
$opt=$db->getOption($data);
$this->assign('opt',$opt);
$this->assign('cates',$data);
return $this->fetch();
}
public function doAdd(){
//执行添加数据
$db=Db::name('categroy1');
if($db->insert()){
$this->success('添加成功',url('index'));
}else{
$this->error('添加失败',url('index'));
}
return $this->fetch();
}

    模型
    

class CategoryModel extends Model{

#通过上级分类的主键id号查询子类
public function getTree($pid=0){
    $data=$this->where('pid='.$pid)->select();
    foreach($data as &$cate){
        #通过该分类的主键id查询该分类的子类
        $cate['cates']=$this->getTree($cate['id']);
    }
    return $data;
}

#拼装属性结构
#通过一个数组组装option
public function getOption($data){
    static $i=0;
    for($n=0;$n<=$i*2;$n++){
        $prefix.="-";
    }
    foreach ($data as $cate) {
        $opt.="";
        #判断该分类下是否包含子类,如果有子类,将数组传入接着拼装
        if(!empty($case['cates'])){
            $i++;
            $opt.=$this->getOption($case['cases']);
        }else{
            $i=0;
        }
        return $opt;
    }
}

}