PHP递归实现层级树状展开的方法
程序员文章站
2022-04-02 10:27:02
...
这篇文章主要为大家详细介绍了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递归实现层级树状展开的方法的详细内容,更多请关注其它相关文章!
上一篇: 用js怎么动态插入行!_PHP教程
下一篇: curl上传文件版本差异问题解析