PHP Recursive class returning NULL

2019-08-28 08:05发布

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);

2条回答
一夜七次
2楼-- · 2019-08-28 08:39

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']);
查看更多
forever°为你锁心
3楼-- · 2019-08-28 08:50

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; 
    }

}
查看更多
登录 后发表回答