一個更簡單的無限級分類菜單代碼
首先要感謝terry39的指點(diǎn),元旦閑來無事,我就把他所講的原理簡單實(shí)現(xiàn)一下,這個程序的關(guān)鍵就在于數(shù)據(jù)表的設(shè)計(jì)很有特色,不用遞歸,依靠個簡單SQL語句就能列出菜單,看看這個數(shù)據(jù)表怎么設(shè)計(jì)的:
數(shù)據(jù)庫字段大概如下:
-----------------------------------------------------------------------------------
id 編號
fid 父分類編號
name 分類名
path 分類路徑,以 id 為節(jié)點(diǎn),組成類似 ,1,2,3,4, 這樣的字符串
----------------------------------------------------------------------------------
可以假設(shè)有如下的數(shù)據(jù)
id fid name path
----------------------------------------------------
1 0 分類1 ,1,
2 0 分類2 ,2,
3 1 分類1-1 ,1,3,
4 1 分類1-2 ,1,4,
5 2 分類2-1 ,2,5,
6 4 分類1-2-1 ,1,4,6,
----------------------------------------------------
這次偷懶,我只用一個頁面,好在代碼不長,全部代碼用類封裝的(不是必要,而是自己也想熟悉一下OO,呵呵?。?,來看看頁面代碼:
<?php
/**************************************
頁面:menu.php
作者:輝老大
功能:定義數(shù)據(jù)庫操作及生成菜單列表類
**************************************/
class menu{
//創(chuàng)建構(gòu)造函數(shù),作用:數(shù)據(jù)庫連接并選擇相應(yīng)數(shù)據(jù)庫
public function __construct(){
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "7529639";
$dbname = "menu";
mysql_connect($dbhost,$dbuser,$dbpassword) or die("error!");
mysql_query("SET NAMES 'GBK'");
mysql_select_db($dbname);
}
//執(zhí)行SQL語句函數(shù)
private function query($sql){
return mysql_query($sql);
}
//取得結(jié)果集數(shù)組函數(shù)
private function loop_query($result){
return mysql_fetch_array($result);
}
//列出菜單列表函數(shù)
public function menulist(){
$sql="select * from list order by path";
$result=$this->query($sql);
while($rows=$this->loop_query($result)){
if(substr_count($rows['path'],',')>2){
for($i=0;$i<(substr_count($rows['path'],',')-2);$i++)
echo ' ';
}
echo $rows['name'].'<br>';
}
}
//創(chuàng)建析構(gòu)函數(shù),作用:關(guān)閉數(shù)據(jù)庫連接
public function __destruct(){
return mysql_close();
}
}
$db=new menu();//生成實(shí)例
$db->menulist();//調(diào)用方法生成菜單
?>
相關(guān)文章
PHP CURL CURLOPT參數(shù)說明(curl_setopt)
這篇文章主要介紹了PHP CURL CURLOPT參數(shù),需要的朋友可以參考下2013-09-09php面向?qū)ο笕ヂ?(十四) php5接口技術(shù)
PHP 與大多數(shù)面向?qū)ο缶幊陶Z言一樣,不支持多重繼承.也就是說每個類只能繼承一個父類。2009-09-09