PHP uses recursion to generate the Document Tree
When writing recursive functions, you can consider caching and defining static variables to store the last running result. It is very helpful to run multiple programs. the general steps are as follows: First fetch data from the database, put it into an array, convert the data into a tree-like array, and finally convert the tree-like array into html code. Let's look at an instance.
Because one of my own technical sites focuses on articles and some articles are in a series, I want to classify these articles into one class.
The database is well designed and can be categorized by id and fatherid. fatherid indicates that the parent class is the id of the article, and id is the unique id of the article. The layers are not limited and can be two layers, it can be three layers. If the fatherid is 0, it indicates the top-level article.
Php code, mainly Recursion
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Function category_tree ($ fatherid ){ // Require_once ("mysql_class/config. inc. php "); // Require_once ("mysql_class/Database. class. php "); $ Db = new Database (DB_SERVER, DB_USER, DB_PASS, DB_DATABASE ); $ Db-> connect (); $ SQL = "SELECT id, title, url FROM". TABLE_TASK ." WHERE fatherid = $ fatherid and ispublic = 1 order by id asc "; $ Articles = $ db-> query ($ SQL ); $ Db-> close (); While ($ record = $ db-> fetch_array ($ articles )){ $ I = 0; If ($ I = 0 ){ If ($ fatherid = 0 ){ Echo '<ul class = "article-list-no-style border-bottom"> '; } Else { Echo '<ul class = "article-list-no-style"> '; } } If ($ fatherid = 0 ){ Echo '<li> <span class = "glyphicon-log-in" Aria-hidden = "true" id = "han '. $ record ['id'].'"> </Span> <a href = "'. $ record ['url'].'" target = "_ blank">' . $ Record ['title']. '</a> '; } Else { Echo '<li> <span class = "glyphicon-chevron-right" aria-hidden = "true"> </Span> <a href = "'. $ record ['url'].'" target = "_ blank">' . $ Record ['title']. '</a> '; } Category_tree ($ record ['id']); Echo '</li> '; $ I ++; If ($ I> 0 ){ Echo '</ul> '; } } } |
Call:
?
| 1 |
Category_tree (0) // extract the top-level article first |
The above is all the content of this article. I hope you will like it.