您好,欢迎访问一九零五行业门户网

thinkphp实现无限分类(使用递归)_javascript技巧

本文实例为大家分享了thinkphp实现无限分类的详细代码,希望对大家学习无限分类有所启发。
数据库:test
数据表:(tp_category):
common/conf/config.php
'db_config2' => 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
/* * 递归遍历 * @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
public function test() { $category = m('category', '', c('db_config2'))->select(); $result = loop($category); var_dump($result); $this->assign('list', $result); $this->display();}
在模板(view/index/test.html)中输出(仅支持2级分类,如果想全部显示,建议先把数组转换成json格式,然后通过ajax请求,js生成)
{$vo.category} {$cate.category}
后续(ajax请求,递归显示所有分类):
方法 controller/indexcontroller.class.php
public function test() { $this->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
分类测试
另一种无限级分类:
/** * 无限极分类 * @param [type] $cate [description] * @param integer $pid [description] * @param integer $level [description] * @param string $html [description] * @return [type] [description] */function sortout($cate,$pid=0,$level=0,$html='--'){ $tree = array(); foreach($cate as $v){ if($v['pid'] == $pid){ $v['level'] = $level + 1; $v['html'] = str_repeat($html, $level); $tree[] = $v; $tree = array_merge($tree, sortout($cate,$v['id'],$level+1,$html)); } } return $tree;}
js递归(特殊):
这个函数相当于实现php的str_repeat函数
/* 字符串重复函数 */if(!string.str_out_times) { string.prototype.str_out_times = function(l) { return new array(l+1).join(this); }}
// 定位到当前选择function recursion(selector, data, j, pid) { var space = ' ┠ '; if(!data) return false; $.each(data, function(i, item) { var opt = $(''+space.str_out_times(j)+item.name+'');selector.append(opt); if(item.son && (item.son).length>0) { recursion(selector, item.son, ++j); j=0; } }); // 当前是哪个分类 selector.find('option').each(function() { if($(this).val() == pid) { $(this).attr('selected', 'selected'); } });}
为什么j=0呢。因为执行顺序感觉与php不同,这里是从上到下加载。。
ajax请求数据:
$('.btn-edit').click(function() { var id = $(this).data('id'); $.post({:u('article/editarticle')}, {id: id}, function(res) { // 分类 $('[name=pid]').html(''); recursion($('[name=pid]'), res.sort, 0, res.pid); $('[name=id]').val(res.id); $('[name=title]').val(res.title); $('[name=summary]').val(res.summary); $('#thumbnailimg').attr('src', __upload__+'/thumbnail/'+res.thumbnail); ue.setcontent(res.content); $('#modal-edit').modal('show'); });});
以上就是thinkphp实现无限分类的方法,希望对大家的学习有所帮助。
其它类似信息

推荐信息