PHP 递归实现层级树状展现数据_PHP_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > PHP > PHP 递归实现层级树状展现数据

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

 2012/6/11 0:13:47  yl.fighter  程序员俱乐部  我要评论(0)
  • 摘要:<?php$db=mysql_connect('localhost','root','root')ordie('Can\'tconnecttodatabase');mysql_select_db('test')ordie('Can\'tfinddatabase:test');$result=mysql_query('selectid,fid,namefromtree');while($arr=mysql_fetch_array($result)){$data[]=array
  • 标签: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('&nbsp;&nbsp;&nbsp;&nbsp;', $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(! empty($leaf['children'])) tree2html($leaf['children']);
        echo '</li>';
    }
    echo '</ul>';
}

tree2html($tree);

?

?

?

图 1:

?图 2:



??图 3:


  • 大小: 11.6 KB
  • 大小: 25.3 KB
  • 大小: 11.9 KB
  • 查看图片附件
发表评论
用户名: 匿名