Home >Web Front-end >JS Tutorial >thinkphp implements unlimited classification (using recursion)_javascript skills

thinkphp implements unlimited classification (using recursion)_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:24:352548browse

The example in this article shares with you the detailed code of thinkphp to implement infinite classification. I hope it will inspire everyone to learn infinite classification.

Database: test
Data table: (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 traverse function 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();
}

Output in the template (View/Index/test.html) (only supports level 2 classification. If you want to display all, it is recommended to convert the array into JSON format first, and then request through AJAX and generate JS)

<ul>
 <volist name="list" id="vo">
 <li>
 {$vo.category}
 <notempty name="vo['children']">
 <ul>
  <volist name="vo['children']" id="cate">
  <li>{$cate.category}</li>
  </volist>
 </ul>
 </notempty>
 </li>
 </volist>
</ul>

Follow-up (ajax request, recursively display all categories):

Method 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'=>'获取列表成功'));
}

Template View/Index/test.html

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
 <title>分类测试</title>
 <script src="__PUBLIC__/js/jquery.min.js"></script>
</head>
<body>
<ul id="menu"></ul>

<script>
 $(function() {

 // 递归列表函数
 function recursion(selector,data)
 {
 if(!data) return false;

 for(var i=0;i<data.length;i++)
 {
 var li=$('<li>'+data[i]['category']+'</li>');

 if(data[i]['children'] && data[i]['children'].length>0)
 {
  var ul=$('<ul></ul>');
  recursion(ul,data[i]['children']);
  li.append(ul);
 }

 selector.append(li);
 }
 }

 // ajax请求 用$.post() 会更方便
 $.ajax({
 url: "{:U('resultCategory')}",
 type: 'post',
 dataType: 'json',
 error: function(res) {
 console.log(res);
 },
 success: function(res) {
 recursion($('#menu'),res['data']);

 console.log(res['data']);
 }
 });
 });
</script>

</body>
</html>

Another infinite classification:

/**
 * 无限极分类
 * @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 recursion (special):

This function is equivalent to implementing PHP’s str_repeat function

/* 字符串重复函数 */
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 = $('<option value="'+item.id+'">'+space.str_out_times(j)+item.name+'</option>');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');
 }
 });
}

Why j=0. Because the execution order feels different from php, it is loaded from top to bottom. .

ajax request data:

$('.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');
 });
});

The above is how thinkphp implements unlimited classification. I hope it will be helpful to everyone's learning.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn