thinkphp 無線層級分類
name id parent_id path
新聞 1 0 0
中國新聞 2 1 0-1
河北新聞 3 2 0-1-2
保定新聞 0-1-2-3
美國新聞 4 1 0-1
紐約新聞 5 4 0-1-4
華爾街新聞6 5 0-1-4-5
俄羅斯新聞 7 1 0-1
資料庫欄位
mysql> select * from news;
+---------+-----------+------+---------+
| news_id | news_name | pid | path |
+---------+-----------+------+---------+
| 1 | 新聞 | 0 | 0 |
| 2 | 中國新聞 | 1 | 0-1 |
| 3 | 美國新聞 | 1 | 0-1 |
| 4 | 河北新聞 | 2 | 0-1-2 |
| 5 | 紐約新聞 | 3 | 0-1-3 |
| 6 | 邯鄲新聞 | 4 | 0-1-2-4 |
+---------+-----------+------+---------+
6 rows in set (0.00 sec)
以無線層級的思想查看資料庫
mysql> select news_id,news_name,pid,path,concat(path,'-',news_id) as bpath from
news order by bpath;
+---------+-----------+------+---------+-----------+
| news_id | news_name | pid | path | bpath |
+---------+-----------+------+---------+-----------+
| 1 | 新聞 | 0 | 0 | 0-1 |
| 2 | 中國新聞 | 1 | 0-1 | 0-1-2 |
| 4 | 河北新聞 | 2 | 0-1-2 | 0-1-2-4 |
| 6 | 邯鄲新聞 | 4 | 0-1-2-4 | 0-1-2-4-6 |
| 3 | 美國新聞 | 1 | 0-1 | 0-1-3 |
| 5 | 紐約新聞 | 3 | 0-1-3 | 0-1-3-5 |
+---------+-----------+------+---------+-----------+
6 rows in set (0.04 sec)
News_id 自增
Pid :當前的pid是,父級news_id,
Path:當前的path是父級的path連上父級的news_id
bPath:當前的bpath是當前的path欄位加上當前的news_id欄位,他是一個臨時的欄位,這樣就可以排序bpath,就可以達到一級一級的瀏覽的效果
concat()函數的參數是字串列表,返回結果是 連結參數產生的字串
在TP架構中
CategoryAction.class.php
class CategoryAction extends Action{
public function shows(){
header('Content-Type:text/html;charset=utf8');
$model=D('News');
$list=$model->field("news_id,news_name,pid,path,concat(path,'-',news_id) as bpath")->order('bpath')->select();//bPath欄位是path欄位加上news_id欄位
//var_dump($list);
/*php中的foreach,添加count子段,在bpath欄位中,新聞是2個數字(0,1),中國新聞是3個{0,1,2},美國新聞是3個{0,1,3},河北新聞是4個數字(0,1,2,4)...所以要把-橫杠去掉計算bpath的個數,用explode把bpath的字串分割成數組,在計算數位長度,值就是count欄位的內容,縮排的字元數*/
foreach($list as $key=>$value){
//沒迴圈一次就增加一個count欄位,值是由字串分割數組的個數
$list[$key]['count']=count(explode('-',$value['bpath']));//$list[$key]['count']添加一個臨時count欄位
}
$this->assign('list',$list);
$this->display();
}
public function add(){
$model=D('News');
$data=array(
'news_name'=>$_POST['uname'],
'pid'=>$_POST['pid'],//新添加的父id應該是點擊當前option的id,也就是value="{$vo.news_id}",獲得表單的value值通過的name值 ); if($model->create($data)){ if($model->add()){ $this->success('添加成功'); }else{ $this->error('添加失敗'); } }else{ $this->error($model->getError()); } } } ?>模板中show.html