首頁 >後端開發 >php教程 >PHP 递归兑现层级树状展现数据

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

WBOY
WBOY原創
2016-06-13 10:38:40975瀏覽

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'],     );}// 将数据按照缩进简单排列 见图1function 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/>';// 将数据按照所属关系封装 见图2function 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再次展现 见图3function tree2html($tree) {    echo '<ul>';    foreach($tree as $leaf) {        echo '<li>' .$leaf['name'];        if(! empty($leaf['children'])) tree2html($leaf['children']);        echo '</li>';    }    echo '</ul>';}tree2html($tree);

?

?

?

图 1:

?图 2:



??图 3:


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn