通过PHP与mysql进行递归树遍历 [英] Recursive tree traversal with mysql through PHP

查看:193
本文介绍了通过PHP与mysql进行递归树遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为客户创建一个调查表,该调查表要求将问题按3个层次进行组织.我已经成功创建了U.I.但是,最近3个小时,我一直在尝试从数据库中提取数据,以便将所有内容加载到正确的位置.数据库是由客户端这样组织的,因此我无法控制它:

I am creating a questionnaire for a client that requires the questions to be organized by 3 layers of levels. I've successfully created the U.I. however I've been trying for the last 3 hours to pull data from a database in such a way that everything loads in the right place. The database is organized like so by the client so I have no control over it:

id    description    parentId    
1      Level 1        0           
2      Level 2        0           
3      Level 1a       1   
4      Level 1b       1 
5      Level 1a1      3      

我在网站上发现了一个类似的问题,但是当我尝试解决该问题时,我反复重复以下内容:

I have found a similar question to mine on the site but when I attempted it's solution I got the following on repeat infinetly:

代码:

function makeList($par_id = 0) {
    //your sql code here
    $result = mysql_query("SELECT * FROM pB_test WHERE parentId = $par_id");
    $pages = mysql_fetch_array( $result );

    if (count($pages)) {
        echo '<ul>';
        foreach ($pages as $page) {
            echo '<li>', $page['description'];
                makeList($page['parentId']);
                echo '</li>';
        }
        echo '</ul>';
    }
}

makeList();

输出:

1
3
5
5
l
l
3
5
5
l
l
3
5
5
l
l
3
5
5
l
l

有人知道如何解决此问题以及确切的问题是什么?干杯

Does anyone know how to fix this and what the issue is exactly? Cheers

推荐答案

递归执行此操作:

function printChildQuestions($parentid) {
  $sql="SELECT * FROM pB_test WHERE parentID=$parentid";
  $result=mysql_query($sql);
  $i=0;
  while (true) {
    $row=mysql_fetch_array($result);
    if (!$row) break;
    if ($i==0) echo "<ul>";
    $i=1;
    echo '<li>'.$row['id'].'&nbsp;'.$row['description'].'&nbsp;'.$row['parentId'].'</li>';
    printChildQuestions($row['id']);
  }
  if ($i>0) echo '</ul>';
}

printChildQuestions(0);

这篇关于通过PHP与mysql进行递归树遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆