php 无限级分类 递归+sort排序 和 非递归

1 先总结非递归

数据表:

id name pid path
1 php 0 0
2 mysql 0 0
3 linux 0 0
4 php-基本语法 1 0-1
5 linux-磁盘分区 3 0-3
 1 <?php
 2 
 3 $navArr = [
 4   [
 5       'name'=>'php',
 6       'id'=>1,
 7       'pid'=>0,
 8       'path'=>'0',
 9       'sort'=>'2',
10 
11   ],
12     [
13         'name'=>'php-基础',
14         'id'=>2,
15         'pid'=>1,
16         'path'=>'0-1',
17         'sort'=>'2',
18 
19     ],
20     [
21         'name'=>'php-面向对象',
22         'id'=>5,
23         'pid'=>1,
24         'path'=>'0-1',
25         'sort'=>'1',
26 
27     ],
28     [
29         'name'=>'php-面向对象-属性',
30         'id'=>6,
31         'pid'=>5,
32         'path'=>'0-1-5',
33         'sort'=>'2',
34 
35     ],
36     [
37         'name'=>'php-面向对象-访问权限',
38         'id'=>7,
39         'pid'=>5,
40         'path'=>'0-1-5',
41         'sort'=>'1',
42 
43     ],
44     [
45         'name'=>'服务端',
46         'id'=>3,
47         'pid'=>0,
48         'path'=>'0',
49         'sort'=>'3',
50 
51     ],
52     [
53         'name'=>'mysql',
54         'id'=>4,
55         'pid'=>0,
56         'path'=>'0',
57         'sort'=>'1',
58 
59     ],
60     [
61         'name'=>'linux',
62         'id'=>5,
63         'pid'=>3,
64         'path'=>'0-3',
65         'sort'=>'3',
66 
67     ],
68 ];
69 
70 foreach($navArr as $k => &$item){
71     $num = substr_count($item['path'],'-');
72     $pre = $sortPath = '';
73     if($num >0)
74     {
75         $tree = '|'.str_repeat(' -- ',$num).$item['name'];
76     }else{
77         $tree = $item['name'];
78         $sortPath = $item['sort'];
79     }
80     $item['tree'] = $tree;
81     $arr[] = $item['path'].'-'.$item['id'];
82 }
83 
84 array_multisort($arr,SORT_STRING,$navArr);
85 
86 foreach($navArr as $item2)
87 {
88     echo $item2['tree'].'<br/>';
89 }
90 
91 

 此无限级分类没有处理 分类排序有效,以后更改。

2 递归+排序

猜你喜欢

转载自www.cnblogs.com/liujie-php/p/10159378.html