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

Posted 孤舟残月浅笑嫣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 递归实现层级树状展现数据相关的知识,希望对你有一定的参考价值。

<?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\'],   
    );  
}  
   
// 将数据按照缩进简单排列 见图1  
function data2arr($tree, $rootId = 0, $level = 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/>\';  
   
// 将数据按照所属关系封装 见图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/>-----------------------------------------------------------------------<br/>\';  
   
// 将数据使用html再次展现 见图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);

以上是关于PHP 递归实现层级树状展现数据的主要内容,如果未能解决你的问题,请参考以下文章

PHP使用递归按层级查找数据

浅谈oracle树状结构层级查询测试数据

php递归

React+AntDesign使用Tree树控件完整展现其中的层级关系,并具有展开收起选择等交互功能

PHP原生递归实现无限级分类树状展示数据

HTML5的WebGL实现的3D和2D拓扑树