首页  >  文章  >  后端开发  >  PHP 递归实现层级树状展现数据

PHP 递归实现层级树状展现数据

巴扎黑
巴扎黑原创
2016-11-23 13:13:361459浏览

<?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);

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:PHP 排列组合下一篇:PHP之引用