如果要爲應用程序創建n級菜單,則需要遞歸功能。
先加 「父」 ID字段到表:下面的函數
CREATE TABLE IF NOT EXISTS `menus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`parent` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `menus` (`id`, `title`, `parent`) VALUES
(1, 'Menu 1', 0),
(2, 'Menu 2', 0),
(3, 'Sub Menu 1', 1),
(4, 'Sub Menu 2', 1),
(5, 'Sub Menu 3', 2);
和使用產生n級菜單:
:
createmenu(0); // Enter root menu id
function createmenu($pid) {
if($pid == 0) { echo "<ul>"; }
$query = "select * from menus where parent = $pid";
$run = mysql_query($query);
$count = mysql_affected_rows();
if($count > 0) {
echo "<ul>";
while($row=mysql_fetch_array($run)){
$id = $row[0];
$m_title = $row[1];
echo "<li><a href='pages.php?pages=$m_title'>$m_title</a>";
$q = "select * from menus where parent = $id";
$r = mysql_query($q);
$c = mysql_affected_rows();
if($c > 0) {
createmenu($id);
}
echo "</li>";
}
echo "</ul>";
}
if($pid == 0) { echo "</ul>"; }
}
你會得到下面的輸出
<ul>
<ul>
<li><a href='pages.php?pages=Menu 1'>Menu 1</a>
<ul>
<li><a href='pages.php?pages=Sub Menu 1'>Sub Menu 1</a></li>
<li><a href='pages.php?pages=Sub Menu 2'>Sub Menu 2</a></li>
</ul>
</li>
<li><a href='pages.php?pages=Menu 2'>Menu 2</a>
<ul>
<li><a href='pages.php?pages=Sub Menu 3'>Sub Menu 3</a></li>
</ul>
</li>
</ul>
</ul>