php递归树形菜单

-- 数据库: `news_php100`

CREATE TABLE `menu` (
  `id` tinyint(4) NOT NULL auto_increment,
  `parent_id` tinyint(4) NOT NULL default '0',
  `name` varchar(20) default NULL,
  `url` varchar(60) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=18 ;

INSERT INTO `menu` (`id`, `parent_id`, `name`, `url`) VALUES
(1, 0, '人事管理', ''),
(2, 0, '通讯交流', ''),
(3, 1, '档案管理', ''),
(4, 1, '考勤管理', 'http://localhost/personal/attendance.php'),
(5, 2, '通讯录', ''),
(6, 2, '网络会议', ''),
(7, 3, '新增档案', 'http://localhost/personal/add_achive.php'),
(8, 3, '查询档案', 'http://localhost/personal/search_archive.php'),
(9, 3, '删除档案', 'http://localhost/personal/delete_archive.php'),
(10, 5, '新增通讯记录', 'http://localhost/communication/add_address.php'),
(11, 5, '查询通讯记录', 'http://localhost/communication/search_address.php'),
(12, 5, '删除通讯记录', 'http://localhost/communication/delete_address.php'),
(13, 6, '召开会议', 'http://localhost/communication/convence_meeting.php'),
(14, 6, '会议查询', 'http://localhost/communication/search_meeting.php'),
(15, 13, '处理方式', NULL),
(16, 13, '两条腰上', NULL),
(17, 15, '把三角形', NULL);

<?php
header("Content-type: text/html; charset=utf-8"); 
$link=mysql_connect("localhost","root","");
mysql_select_db("news_php100");
mysql_query("SET NAMES utf8");
$query="select * from menu where parent_id=0";
$res=mysql_query($query,$link);
if (mysql_num_rows($res)>0)
	show_menu($link,$res);
	
function show_menu($link,$res,$depth=0){
	$num=mysql_num_rows($res);
	for ($i=0;$i<$num;$i++){
		$menu=mysql_fetch_array($res);
		echo str_repeat("&nbsp;",4*$depth);
		echo $menu[name].'<br>';
		$sql="select * from menu where parent_id=$menu[id]";
		$res_sub=mysql_query($sql,$link);
		if (mysql_num_rows($res_sub)>0){
			show_menu($link,$res_sub,$depth+1);
		}
	}
}
?>

你可能感兴趣的:(PHP)