日期:2011-04-20  浏览次数:20590 次


代码:--------------------------------------------------------------------------------
CREATE TABLE `tree1` (
`id` tinyint(3) unsigned NOT NULL auto_increment,
`parentid` tinyint(3) unsigned NOT NULL default '0',
`topic` varchar(50) default NULL,
PRIMARY KEY (`id`),
KEY `parentid` (`parentid`)
) TYPE=MyISAM;

INSERT INTO `tree1` (`id`, `parentid`, `topic`) VALUES
(1,0,'树1'),
(2,0,'树2'),
(3,0,'树3'),
(4,2,'树2-1'),
(5,4,'树2-1-1'),
(6,2,'树2-2'),
(7,1,'树1-1'),
(8,1,'树1-2'),
(9,1,'树1-3'),
(10,8,'树1-2-1'),
(11,7,'树1-1-1'),
(12,11,'树1-1-1-1');
--------------------------------------------------------------------------------


字段说明
id,记录的id号
parentid,记录的父记录id(为0则为根记录)
topic,记录的显示标题

显示程序

顺序树:

PHP代码:--------------------------------------------------------------------------------

<?
/* 数据库连接 */
mysql_connect();
mysql_select_db('tree');

/* 树状显示的递归函数 */
function tree($parentid = 0) {
/*执行sql查询,获取记录的标题和id*/
$sql = "select topic,id from tree1 where parentid = $parentid order by id asc";
$rs = mysql_query($sql);
/* 缩进*/
echo("<ul>");
while($ra = mysql_fetch_row($rs)) {
/* 显示记录标题 */
echo('<li>'.$ra[0].'</li>');
/* 递归调用 */
tree($ra[1]);
}
echo("</ul>");
}
tree();
?>

--------------------------------------------------------------------------------


逆序树:

PHP代码:--------------------------------------------------------------------------------

<?
/* 数据库连接 */
mysql_connect();
mysql_select_db('tree');

/* 树状显示的递归函数 */
function tree($parentid = 0) {
/*执行sql查询,获取记录的标题和id*/
$sql = "select topic,id from tree1 where parentid = $parentid order by id desc";
$rs = mysql_query($sql);
/* 缩进*/
echo("<ul>");
while($ra = mysql_fetch_row($rs)) {
/* 显示记录标题 */
echo('<li>'.$ra[0].'</li>');
/* 递归调用 */
tree($ra[1]);
}
echo("</ul>");
}
tree();
?>

--------------------------------------------------------------------------------


插入数据程序

PHP代码:--------------------------------------------------------------------------------

<?
/* 数据库连接 */
mysql_connect();
mysql_select_db('tree');
$sql = "insert into tree (topic,parentid) values('树3-1',3);";
mysql_query($sql);
?>

--------------------------------------------------------------------------------


2。排序字段法
此方法是通过在数据结构中增加一个标志记录在整个树中的顺序位置的字段来实现的。特点是显示速度和效率高。但在单个树的结构复杂的情况下,数据写入效率有所不足。而且顺序排列时候,插入,删除记录的算法过于复杂,故通常用逆序排列。

数据结构(以mysql为例)

代码:--------------------------------------------------------------------------------
CREATE TABLE `tree2` (
`id` tinyint(3) unsigned NOT NULL auto_increment,
`parentid` tinyint(3) unsigned NOT NULL default '0',
`rootid` tinyint(3) unsigned NOT NULL default '0',
`layer` tinyint(3) unsigned NOT NULL default '0',
`orders` tinyint(3) unsigned NOT NULL default '0',
`topic` varchar(50) default NULL,
PRIMARY KEY (`id`),
KEY `parentid` (`parentid`),
KEY `rootid` (`rootid`)
) TYPE=MyISAM