Recursive need help

I have this table

mytree

pid   mem

0        1

1        5

1        6

5        7

5        8


7        9


7         10

I have this function to get the data

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']];

            $rec = $this->display_children($row['mem'], $level + 1, $rec);
        }
    }
    catch(PDOException $ex){
        return $ex->getMessage();
        
    }

    return $rec;
}

First call

echo json_encode(display_children(5, 0));

but I only get this result

5           7

5           8

7           9

7           10

How can include the parent id 1 and memberid 5 ?,like this

parentid memid

1           5

Thank you in advance.

Surely that’s correct though? You’ve called the function with the pid of 5, so it runs through everything with a pid=5 and returns that, and recurses through each of those rows and returns the children it finds. To include the additional selection, wouldn’t you just call

echo json_encode(display_children(1,0));

which in theory would read records where pid=1, then recurse down each of those branches?

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