This article introduces the example code for Recursive Generation of tree lines in PHP.
- <? Php
- Header ("content-type: text/html; charset = UTF-8 ");
- $ Connect = mysql_connect (localhost, root, 123456 );
- Mysql_select_db ("wz ");
- Mysql_query ("set names utf8 ");
- // Obtain the top node
- $ SQL = "select id, name, ischild from tree where parent = 0 order by id asc ";
- $ Result = mysql_query ($ SQL );
- While ($ row = mysql_fetch_array ($ result ))
- {
- Extract ($ row );
- // If a subnode exists, add an event to it to expand or close the subnode.
- $ Icon = $ ischild? "<A href = javascript.: expand (" div $ id ");> </a> ":"-";
- $ Name = $ icon. $ name;
- Echo "<div id = div". $ id. ">". $ name;
- If ($ ischild)
- {
- // Recursively retrieve nodes
- GetNode ($ id, 0 );
- }
- Echo "</div> ";
- }
- Function getNode ($ id, $ level)
- {
- $ SQL = "select id, name, ischild from tree where parent = $ id order by id asc ";
- $ Result = mysql_query ($ SQL );
- $ Level;
- While ($ row = mysql_fetch_array ($ result ))
- {
- Extract ($ row );
- $ Icon = $ ischild? "<A href = javascript.: expand (" div $ id ");> </a> ":"-";
- $ Name = $ icon. $ name;
- Echo "<div id = div". $ id. ">". echoChar ("", $ level). $ name;
- If ($ ischild)
- {
- GetNode ($ id, $ level );
- }
- Echo "</div> ";
- }
- }
- Function echoChar ($ char, $ num)
- {
- For ($ I = 0; $ I <$ num; $ I)
- {
- $ StrChar. = $ char;
- }
- Return $ strChar;
- }
- ?>
- <Script language = "javascript">
- Function expand (id)
- {
- Var obj = document. getElementById (id). childNodes;
- For (var I = 0; I <obj. length; I)
- {
- If (obj [I]. nodeName = "DIV ")
- {
- Switch (obj [I]. style. display)
- {
- Case "":
- Case "block ":
- Obj [I]. style. display = "none ";
- Break;
- Case "none ":
- Obj [I]. style. display = "block ";
- Break;
- }
- }
- }
- }
- </Script>