限制孩子在树上数到6级

时间:2014-10-14 11:55:10

标签: php mysql

我创建的php函数以树形式获取父项的所有子项。问题是它得到了所有的孩子,但我想限制它直到树的第6级。我做的代码是

get_childs("2");

function get_childs($parent_id){
GLOBAL $con;
     if ($result = mysqli_query($con,"SELECT * FROM user_profile WHERE referred_by='$parent_id'")) {
         echo '<ul>';

         while ($row = $result->fetch_assoc()) {
             echo '<li><a href="#">'.$row['user_id'].'</a>';

             //call again for each child. if the id dosen't have childs, then prints nothing and go on!
             get_childs($row['user_id']);

             echo '</li>';
        }// end while

        echo '</ul>';
     }// end if select

} 

它生成的输出

enter image description here

我希望将其限制为17,如上面的输出那样,第6级到达那里。

2 个答案:

答案 0 :(得分:2)

根据我的评论,我建议这样的事情:

get_childs("2", 0);

function get_childs($parent_id, $level){
    GLOBAL $con;
    if ($result = mysqli_query($con,"SELECT * FROM user_profile WHERE referred_by='$parent_id'")) {
         echo '<ul>';

         while ($row = $result->fetch_assoc()) {
             echo '<li><a href="#">'.$row['user_id'].'</a>';

             //call again for each child. if the id dosen't have childs, then prints nothing and go on!
            if($level < 6)
                get_childs($row['user_id'], $level + 1);

            echo '</li>';
        }// end while

        echo '</ul>';
    }// end if select
}

通过这个微小的改动,一旦达到第6级,你的树就会停止。 (你可能需要稍微调整一下)

答案 1 :(得分:2)

get_childs("2", 6);

function get_childs($parent_id, $level){
    if($level < 1) return false;
GLOBAL $con;
     if ($result = mysqli_query($con,"SELECT * FROM user_profile WHERE referred_by='$parent_id'")) {
         echo '<ul>';

         while ($row = $result->fetch_assoc()) {
             echo '<li><a href="#">'.$row['user_id'].'</a>';

             //call again for each child. if the id dosen't have childs, then prints nothing and go on!
             get_childs($row['user_id'], $level--);

             echo '</li>';
        }// end while

        echo '</ul>';
     }// end if select

}