网站群建设公司,男的和女的做那个视频网站,还是新能源专业好,网站推广软件哪个最实惠thinkphp实现无限分类#xff08;使用递归#xff09; 本文实例为大家分享了thinkphp实现无限分类的详细代码#xff0c;希望对大家学习无限分类有所启发。
数据库#xff1a;test
数据表#xff1a;#xff08;tp_category#xff09;#xff1a;
Common/conf/conf…thinkphp实现无限分类使用递归 本文实例为大家分享了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, $id0) {
$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}
后续(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,status1,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,$pid0,$level0,$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],$level1,$html));
}
}
return $tree;
}
JS递归特殊
这个函数相当于实现php的str_repeat函数
/* 字符串重复函数 */
if(!String.str_out_times) {
String.prototype.str_out_times function(l) {
return new Array(l1).join(this);
}
}
// 定位到当前选择
function recursion(selector, data, j, pid) {
var space ┠ ;
if(!data) return false;
$.each(data, function(i, item) {
var opt $(
);selector.append(opt);
if(item.son (item.son).length0) {
recursion(selector, item.son, j);
j0;
}
});
// 当前是哪个分类http://
selector.find(option).each(function() {
if($(this).val() pid) {
$(this).attr(selected, selected);
}
});
}
为什么j0呢。因为执行顺序感觉与php不同这里是从上到下加载。。
ajax请求数据
$(.btn-edit).click(function() {
var id $(this).data(id);
$.post({:U(Article/editArticle)}, {id: id}, function(res) {
// 分类
$([namepid]).html();
recursion($([namepid]), res.sort, 0, res.pid);
$([nameid]).val(res.id);
$([nametitle]).val(res.title);
$([namesummary]).val(res.summary);
$(#thumbnailImg).attr(src, __UPLOAD__/thumbnail/res.thumbnail);
ue.setContent(res.content);
$(#modal-edit).modal(show);
});
});
以上就是thinkphp实现无限分类的方法希望对大家的学习有所帮助。