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 递归+排序
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: Administrator 5 * Date: 2018/12/21 6 * Time: 19:44 7 */ 8 9 $navList = [ 10 [ 11 'id'=>1, 12 'name'=>'php', 13 'pid'=>0, 14 'sort'=>3, 15 ], 16 [ 17 'id'=>2, 18 'name'=>'mysql', 19 'pid'=>0, 20 'sort'=>2, 21 ], 22 [ 23 'id'=>3, 24 'name'=>'linux', 25 'pid'=>0, 26 'sort'=>1, 27 ], 28 [ 29 'id'=>4, 30 'name'=>'javascript', 31 'pid'=>0, 32 'sort'=>0, 33 ], 34 [ 35 'id'=>5, 36 'name'=>'php-类型', 37 'pid'=>1, 38 'sort'=>3, 39 ], 40 [ 41 'id'=>9, 42 'name'=>'php-类型-布尔', 43 'pid'=>5, 44 'sort'=>3, 45 ], 46 [ 47 'id'=>6, 48 'name'=>'php-变量', 49 'pid'=>1, 50 'sort'=>2, 51 ], 52 [ 53 'id'=>7, 54 'name'=>'php-常量', 55 'pid'=>1, 56 'sort'=>4, 57 ], 58 [ 59 'id'=>8, 60 'name'=>'linux-磁盘分区', 61 'pid'=>3, 62 'sort'=>5, 63 ], 64 ]; 65 $arr = getTree(0); 66 v($arr); 67 function getTree($pid=0,$level=1) 68 { 69 global $navList; 70 $childs = getChild($navList,$pid,$level); 71 array_multisort(array_column($childs,'sort'),SORT_NUMERIC,$childs); 72 foreach($childs as $key => $navItem) 73 { 74 75 $resChild = getTree($navItem['id'],$level+1); 76 if(null != $resChild) 77 { 78 $childs[$key]['child'] = $resChild; 79 } 80 81 } 82 return $childs; 83 } 84 85 function getChild(&$arr,$id,$lev) 86 { 87 $child = []; 88 foreach($arr as $k => $value) 89 { 90 91 if($value['pid'] == $id) 92 { 93 $value['level'] = $lev; 94 $child[] = $value; 95 } 96 } 97 return $child; 98 } 99 100 function v($data) 101 { 102 echo '<pre>'; 103 var_dump($data);exit; 104 }