Two methods to implement tree structure
1. Recursive method
Recursion is when a function explicitly calls itself.
The characteristics of using the recursive method to realize the tree structure are that the data writing speed is faster and the display speed is slower (especially obvious when the tree has many branches/levels). It is suitable for situations where the amount of written data is large and the tree structure is complex.
Data structure (take mysql as an example)
Code:------------------------------------------------ --------------------------------
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,'Tree 1'),
(2,0,'tree2'),
(3,0,'Tree 3'),
(4,2,'Tree 2-1'),
(5,4,'Tree 2-1-1'),
(6,2,'Tree 2-2'),
(7,1,'Tree 1-1'),
(8,1,'Tree 1-2'),
(9,1,'Tree 1-3'),
(10,8,'Tree 1-2-1'),
(11,7,'Tree 1-1-1'),
(12,11,'Tree 1-1-1-1');
-------------------------------------------------- ----------------------------------
Field Description
id, the recorded id number
parentid, the parent record id of the record (if it is 0, it is the root record)
topic, the record’s display title
Show program
Sequence tree:
PHP code:------------------------------------------------- ----------------------------------
/* Database connection */
mysql_connect();
mysql_select_db('tree');
/* Recursive function displayed in tree format */
function tree($parentid = 0) {
/*Execute sql query to obtain the title and id of the record*/
$sql = "select topic,id from tree1 where parentid = $parentid order by id asc";
$rs = mysql_query($sql);
/* Indent*/
echo("