相思资源网 Design By www.200059.com

本文实例为大家分享了PHP递归实现层级树状展开的主要代码,供大家参考,具体内容如下

效果图:

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(! emptyempty($leaf['children'])) tree2html($leaf['children']); 
    echo '</li>'; 
  } 
  echo '</ul>'; 
} 
  
tree2html($tree);

以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。

标签:
PHP递归实现层级树状,PHP实现层级树状,PHP层级树状

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“PHP递归实现层级树状展开”

暂无PHP递归实现层级树状展开的评论...