PHP Recursive Implementation hierarchical tree expansion, php recursive Hierarchy Tree
The examples in this article share the main code for the hierarchical tree expansion of PHP Recursive Implementation for your reference. The specific content is as follows:
:
Implementation Code:
<? Php $ db = mysql_connect ('localhost', 'root', 'root') or die ('can \'t connect to database'); mysql_select_db ('test ') or die ('can \'t find database: test'); $ result = mysql_query ('select id, fid, name from tree '); while ($ arr = mysql_fetch_array ($ result) {$ data [] = array ('id' => $ arr ['id'], 'fid' => $ arr ['fid'], 'name' => $ arr ['name'],);} // arrange the data according to indentation. See figure 1 function data2arr ($ tree, $ rootId = 0, $ le Vel = 0) {foreach ($ tree as $ leaf) {if ($ leaf ['fid'] = $ rootId) {echo str_repeat ('', $ level ). $ leaf ['id']. ''. $ leaf ['name']. '<br/>'; foreach ($ tree as $ l) {if ($ l ['fid'] = $ leaf ['id']) {data2arr ($ tree, $ leaf ['id'], $ level + 1); break ;}}} data2arr ($ data ); echo '<br/> --------------------------------------------------------------------- <br/>'; // encapsulate the data according to its relationship. See figure 2 function arr2tree ($ Tree, $ rootId = 0) {$ return = array (); foreach ($ tree as $ leaf) {if ($ leaf ['fid'] = $ rootId) {foreach ($ tree as $ subleaf) {if ($ subleaf ['fid'] = $ leaf ['id']) {$ leaf ['children '] = arr2tree ($ tree, $ leaf ['id']); break ;}$ return [] = $ leaf ;}} return $ return;} $ tree = arr2tree ($ data); print_r ($ tree); echo '<br/> encode <br/>'; // set Use HTML to display data again. See figure 3 function tree2html ($ tree) {echo '<ul>'; foreach ($ tree as $ leaf) {echo '<li> '. $ leaf ['name']; if (! Emptyempty ($ leaf ['children ']) tree2html ($ leaf ['children']); echo '</li>';} echo '</ul> ';} tree2html ($ tree );
The above is all the content of this article. I hope it will help you learn php programming.
Articles you may be interested in:
- Analysis on the use of PHP recursive function return values
- Php unlimited classification and support for output tree chart details
- Php recursively retrieves files in the directory (including subdirectories) and shares encapsulation classes
- Considerations for using return in php recursive functions
- Example of php recursion (php recursion function)
- How to Use php function recursion and difference between return and echo
- Php unlimited classification, super simple unlimited classification, support output tree chart
- Php infinitus classification recursive sorting Implementation Method
- Php tree menu code based on Recursion
- Three basic methods for php to implement Recursion