Home  >  Article  >  php教程  >  PHP递归实现层级树状展开,php递归层级树状

PHP递归实现层级树状展开,php递归层级树状

WBOY
WBOYOriginal
2016-06-13 08:42:49981browse

PHP递归实现层级树状展开,php递归层级树状

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

效果图:

实现代码:

<&#63;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递归函数返回值使用方法
  • php无限分类且支持输出树状图的详细介绍
  • php递归获取目录内文件(包含子目录)封装类分享
  • php递归函数中使用return的注意事项
  • php递归使用示例(php递归函数)
  • php function用法如何递归及return和echo区别
  • php 无限级分类,超级简单的无限级分类,支持输出树状图
  • php无限极分类递归排序实现方法
  • 基于递归实现的php树形菜单代码
  • php实现递归的三种基本方式
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn