在TP5公共common.php文件里写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
<?php //计算某个类别所属的类别层数 function getcatelayer( $cateid , $flag =1){ $cates = M( 'Gcategory' ); $ini [ 'cate_id' ] = $cateid ; $arr = $cates ->where( $ini )->find(); if ( $arr [ 'parent_id' ]!=0){ $flag = getcatelayer( $arr [ 'parent_id' ], $flag +1); } return $flag ; } //类别递归(单层) function getone( $arr , $parent =0, $lev =0){ //迭代 $task = array ( $parent ); //任务数组 $tree = array (); //结果数组 while (! empty ( $task )){ $flg =false; foreach ( $arr as $k => $v ){ if ( $v [ 'parent_id' ]== $parent ) { $tree []= array ( 'id' => $v [ 'cate_id' ], 'name' => $v [ 'cate_name' ], 'lev' => $lev ); array_push ( $task , $v [ 'cate_id' ]); $parent = $v [ 'cate_id' ]; $lev = $lev +1; unset( $arr [ $k ]); $flg =true; } } if ( $flg ==false) { array_pop ( $task ); $parent = end ( $task ); $lev = $lev -1; } } return $tree ; } //类别递归(多层) function getCates( $arr , $pid =0) { for ( $i =0; $i < count ( $arr ); $i ++){ if ( $arr [ $i ][ 'parent_id' ]== $pid ){ $newArr [] = array ( "id" => $arr [ $i ][ 'cate_id' ], "name" => $arr [ $i ][ 'cate_name' ], 'son' =>getCates( $arr , $arr [ $i ][ 'cate_id' ]), ); } } return $newArr ; } //查询类别所属级 function getlayer( $cateid , $flg =1) { $gcg =M( "Gcategory" ); $ini [ "cate_id" ]= $cateid ; $cateArr = $gcg ->where( $ini )->find(); if ( $cateArr [ 'parent_id' ]!=0) { $flg =getlayer( $cateArr [ 'parent_id' ], $flg +1); } return $flg ; } |
一般只用其中的递归单层就可以了
控制器中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php //分类管理 namespace app\admin\Controller; use think\Db; use think\Controller; class CategoryController extends Controller { /** * 分类列表页(递归) */ public function category_list() { header( 'content-type:text/html;charset=utf-8' ); $categoryArr =db::name( '表名' )->select(); //调用递归函数 $getall =getone( $categoryArr ); $this ->assign( "getall" , $getall ); return $this ->fetch() } |
视图 view中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<div class = "conShow" > <table border= "1" cellspacing= "0" cellpadding= "0" > <tr> <td width= "100px" class = "tdColor tdC" >id</td> <td width= "150px" class = "tdColor" >汽车类型</td> <td width= "180px" class = "tdColor" >操作</td> </tr> { foreach name= "getall" id= "v" } <tr> <td>{ $v .id}</td> <td >{php} echo str_repeat ( ' ' , $v [ 'lev' ]*2){/php}|-{ $v [ 'name' ]}</td> <td><a href= "connoisseuradd.html" rel= "external nofollow" ><img class = "operation" src= "/img/admin/update.png" ></a> <img class = "operation delban" src= "/img/admin/delete.png" ></td> </tr> {/ foreach } </table> <div class = "paging" >此处是分页</div> </div> |
以上这篇tp5递归 无限级分类详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/php12345679/article/details/79882337