Recursive tree traversal with mysql through PHP

前端 未结 2 446
有刺的猬
有刺的猬 2021-01-19 00:40

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 f

相关标签:
2条回答
  • 2021-01-19 00:56

    it's not good to call mysql server and fetch result each time

    what if you have over 100 rows? or 200+

    use this to query only once:

    $result = mysql_query("SELECT * FROM test");
    $arrs = array();
    
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $arrs[] = $row;
    }
    
    function build_tree($arrs, $parent_id=0, $level=0) {
        foreach ($arrs as $arr) {
            if ($arr['parent_id'] == $parent_id) {
                echo str_repeat("-", $level)." ".$arr['name']."<br />";
                build_tree($arrs, $arr['id'], $level+1);
            }
        }
    }
    
    build_tree($arrs);
    

    common example for table

      id    name    parent_id
    
    0 讨论(0)
  • 2021-01-19 01:15

    Do this recursivly:

    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);
    
    0 讨论(0)
提交回复
热议问题