Home  >  Article  >  Backend Development  >  PHP recursively implements hierarchical tree display of data

PHP recursively implements hierarchical tree display of data

巴扎黑
巴扎黑Original
2016-11-23 13:13:361458browse

<?php
$db = mysql_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;root&#39;) or die(&#39;Can\&#39;t connect to database&#39;);
mysql_select_db(&#39;test&#39;) or die(&#39;Can\&#39;t find database : test&#39;);
$result = mysql_query(&#39;select id, fid, name from tree&#39;);
while($arr = mysql_fetch_array($result)){
    $data[] = array(
        &#39;id&#39; => $arr[&#39;id&#39;], 
        &#39;fid&#39; => $arr[&#39;fid&#39;],
        &#39;name&#39; => $arr[&#39;name&#39;], 
    );
}
// 将数据按照缩进简单排列 见图1
function data2arr($tree, $rootId = 0, $level = 0) {
    foreach($tree as $leaf) {
        if($leaf[&#39;fid&#39;] == $rootId) {
            echo str_repeat(&#39;    &#39;, $level) . $leaf[&#39;id&#39;] . &#39; &#39; . $leaf[&#39;name&#39;] . &#39;<br/>&#39;;
            foreach($tree as $l) {
                if($l[&#39;fid&#39;] == $leaf[&#39;id&#39;]) {
                    data2arr($tree, $leaf[&#39;id&#39;], $level + 1);
                    break;
                }
            }
        }
    }
}
data2arr($data);
echo &#39;<br/>-----------------------------------------------------------------------<br/>&#39;;
// 将数据按照所属关系封装 见图2
function arr2tree($tree, $rootId = 0) {
    $return = array();
    foreach($tree as $leaf) {
        if($leaf[&#39;fid&#39;] == $rootId) {
            foreach($tree as $subleaf) {
                if($subleaf[&#39;fid&#39;] == $leaf[&#39;id&#39;]) {
                    $leaf[&#39;children&#39;] = arr2tree($tree, $leaf[&#39;id&#39;]);
                    break;
                }
            }
            $return[] = $leaf;
        }
    }
    return $return;
}
$tree = arr2tree($data);
print_r($tree);
echo &#39;<br/>-----------------------------------------------------------------------<br/>&#39;;
// 将数据使用HTML再次展现 见图3
function tree2html($tree) {
    echo &#39;<ul>&#39;;
    foreach($tree as $leaf) {
        echo &#39;<li>&#39; .$leaf[&#39;name&#39;];
        if(! empty($leaf[&#39;children&#39;])) tree2html($leaf[&#39;children&#39;]);
        echo &#39;</li>&#39;;
    }
    echo &#39;</ul>&#39;;
}
tree2html($tree);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP permutationsNext article:PHP permutations