Show only specified level

I have this recursive function,and I want only to display the branches up to 10 levels only,but my filtering is not working.

public function display_children($parent,$level, $rec = array()){
    try {
        $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?');

        $cmd->execute(array($parent));

        while ( $row =  $cmd->fetch(PDO::FETCH_ASSOC)) {

            $rec[] = [['v' => $row['mem'], 'f' => $row['mem']], (string)$row['pid'], $row['mem']];
            if($level >10){
                  return $rec;
               exit();
            }
            $rec = $this->display_children($row['mem'], $level + 1, $rec);
        }
    }
    catch(PDOException $ex){
        return $ex->getMessage();

    }

    return $rec;
}

Thank you in advance.

Try changing the if like this

If this doesn’t solve your problem then please specify what “doesn’t work” means

It is still displaying the tree up to 11 levels.

here is my data

INSERT INTO `mytree` (`pid`, `mem`, `position`, `amount`) VALUES
    (8, 27, 'R', 0.00),
    (8, 28, 'L', 0.00),
    (24, 26, 'R', 0.00),
    (0, 1, '', 5500.00),
    (24, 25, 'L', 0.00),
    (21, 24, 'L', 500.00),
    (21, 23, 'R', 0.00),
    (18, 20, 'R', 1500.00),
    (18, 19, 'L', 0.00),
    (15, 18, 'R', 2000.00),
    (15, 17, 'L', 0.00),
    (13, 16, 'L', 0.00),
    (13, 15, 'R', 2500.00),
    (12, 14, 'R', 0.00),
    (12, 13, 'L', 3000.00),
    (10, 12, 'R', 3500.00),
    (10, 11, 'L', 0.00),
    (7, 10, 'R', 4000.00),
    (7, 9, 'L', 0.00),
    (5, 8, 'R', 500.00),
    (5, 7, 'L', 4500.00),
    (1, 6, 'R', 0.00),
    (1, 5, 'L', 5500.00),
    (20, 22, 'R', 0.00),
    (20, 21, 'L', 1000.00);

why is it not working ? if i do this

if($level >10){
  return $rec;
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.