PHP Recursive class returning NULL

2019-08-28 08:36发布

问题:

Please friends, I need help for my code.

My searchParent function always returns NULL when it executes the self:: more than once

class Search {
    public function listParents() {
        $sql = "SELECT id FROM parents";
        return pg_query($sql);
    }

    public function searchParent($id) {
        $parents= $this->listParents($con);
        while ($r = pg_fetch_array($parent)){
            if ($id === $r['id_parent']){
                return $id;
            } 
        }
        $sql = "SELECT id_parent FROM parent WHERE id_parent = $id";
        $query = pg_query($sql);
        $result = pg_fetch_array($query);

        self::searchParent($result['id_parent']);
    }
}

My call, assuming there is the number 230 in the parent table

$id = $search->searchParent(230);

回答1:

You need to bobble the return value of your function.

Before calling the self::searchParent you should add return statement:

return self::searchParent($result['id_parent']);


回答2:

You can optimize the code by using count and left join:

 class Search
{

    public function searchParent($id) {
         $sql = "SELECT count(*) as cnt 
                                FROM 
                                     parents LEFT JOIN parent on parent.id_parent = parents.id 
                                WHERE 
                                      parents.id = $id";
         $query = pg_query($sql);
         $result = pg_fetch_array($query);

         return empty($result['cnt']) ? null : $id; 
    }

}