简体   繁体   English

使用php的递归函数在二叉树中获取级别

[英]recursive function using php for getting level in binary tree

I want to get level in the binary tree. 我想获得二进制树中的级别。 I am getting already tree and insertion point but there is a problem in getting pair matching and level. 我已经在树和插入点上了,但是在获取配对和水平时存在问题。 The binary tree image is attached here 二叉树图像附在这里

how to stop recursive function after level 3. 3级后如何停止递归功能

my code is given below 我的代码如下

function getTree($parent_id, $level){
  global $conn;
  $sql2 = "SELECT * FROM user WHERE parent_id='".$parent_id."' ORDER BY `rightorleft`";
  $result2 = $conn->query($sql2);
  $i=0;
  static $calls=0;
  if (mysqli_num_rows($result2) > 0)
  {
    echo "<ul>";
    while ($row2 = mysqli_fetch_object($result2))
    {
        echo '<li>';
        echo '<div><a href="#"><img src="images/user.png" width="40" height="40"><br>'.$row2->user_id.'</a></div>';
        getTree($row2->id,$level++);   
        echo '</li>'; 
    }
    echo "</ul>";
   }
}

I want to result only for 2 level like this 我想只得到2级像这样

Try using $level as a counter to stop the recursion calls. 尝试使用$level作为计数器来停止递归调用。

By calling the function with $level = 3 should give you the desired result. 通过使用$level = 3调用该函数,可以得到所需的结果。

function getTree($parent_id, $level)
{
    global $conn;

    // Stop when $level is 0 or less
    if($level <= 0) return ;

    $sql2 = "SELECT * FROM user WHERE parent_id='".$parent_id."' ORDER BY `rightorleft`";
    $result2 = $conn->query($sql2);
    $i = 0;
    static $calls = 0;
    if (mysqli_num_rows($result2) > 0)
    {

        echo "<ul>";
        while ($row2 = mysqli_fetch_object($result2))
        {
            echo '<li>';
            echo '<div><a href="#"><img src="images/user.png" width="40" 
            height = "40" >< br > '.$row2->user_id.' </ a ></ div > ';

            // Recursively go deeper, use $level-1 here
            getTree($row2->id,$level-1);
            echo '</li>';
        }
        echo "</ul>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM