1. 程式人生 > >php 無限級分類 遞迴+sort排序 和 非遞迴

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 遞迴+排序