本文实例为大家分享了thinkPHP实现无限分类的详细代码,希望对大家学习无限分类有所启发。
数据库:test 数据表:(tp_category):
Common/conf/config.PHP
array(
'db_type' => 'MysqL','db_user' => 'root','db_pwd' => '','db_host' => 'localhost','db_port' => '3306','db_name' => 'test','DB_PREFIX' => 'tp_',// 数据库表前缀
'DB_CHARSET'=> 'utf8',// 字符集
'DB_DEBUG' => TRUE,// 数据库调试模式 开启后可以记录sql日志 3.2.3新增
),
Common/function.PHP 遍历函数loop
PHP;">
/*
* 递归遍历
* @param $data array
* @param $id int
* return array
* */
function recursion($data,$id=0) {
$list = array();
foreach($data as $v) {
if($v['pid'] == $id) {
$v['son'] = recursion($data,$v['id']);
if(empty($v['son'])) {
unset($v['son']);
}
array_push($list,$v);
}
}
return $list;
}
Controller/IndexController.class.PHP
select();
$result = loop($category);
var_dump($result);
$this->assign('list',$result);
$this->display();
}
在模板(View/Index/test.html)中输出(仅支持2级分类,如果想全部显示,建议先把数组转换成JSON格式,然后通过AJAX请求,JS生成)
方法 Controller/IndexController.class.PHP
display();
}
public function resultCategory() {
$category = M('category',C('DB_CONFIG2'))->select();
$result = loop($category);
$this->ajaxReturn(array('data'=>$result,'status'=>'1','info'=>'获取列表成功'));
}
模板View/Index/test.html
Meta charset="UTF-8">
分类测试