PHP函数不返回值

时间:2010-09-15 11:00:42

标签: php return-value return

我有一个返回值的递归函数。

    public function getparent ($user)
    {
        $referrer=''; $pos=0;$this->setFieldNames();
        $result=mysql_query("select * FROM ". $this->dbtablename ." WHERE ".$this->id_field . " = '$user'", $this->dbConnectionID);
        while($row=mysql_fetch_array($result, MYSQL_ASSOC))
        {
            $referrer=$row['referrer'];
            $export=array();
            foreach($this->tablefields as $val){
                $export[$val] = $row[$val];
            }
        }
        if($referrer != "0" && $referrer != "")
        {
            $result2=mysql_query("select * from " . $this->dbtablename . " where " . $this->id_field . " ='$referrer'", $this->dbConnectionID);
            while($row2=mysql_fetch_array($result2, MYSQL_ASSOC))
            {
                $export=array();
                foreach($this->tablefields as $val){
                    $export[$val] = $row2[$val];
                }
            }
        }

        $result2=mysql_query("select * from " . $this->dbtablename . " where " . $this->parent_id_field . " ='$referrer' order by id asc", $this->dbConnectionID);
        while($row2=mysql_fetch_array($result2, MYSQL_ASSOC))
        {
            $usernames[]=$row2['username'];
        }
        $pos=array_search($user, $usernames);
        if( $referrer == '0' || $pos >=1 )
        {echo 'xxxxxxx';
            return $export;
        }
        else
        {
            $this->getparent($referrer);
        }
    }

似乎当$ referrer为零时,它不返回任何值,但它回显'xxxxxxx'。问题是什么!?

2 个答案:

答案 0 :(得分:2)

有一个问题:

    while($row=mysql_fetch_array($result, MYSQL_ASSOC))
    {
        $referrer=$row['referrer'];
        $export=array();
        foreach($this->tablefields as $val){
            $export[$val] = $row[$val];
        }
    }

你在每次迭代时都要替换你的导出数组 - 这是你的意图吗?除最后一行外,所有数据都被丢弃了。然后在这个块中再次执行:

    if($referrer != "0" && $referrer != "")
    {
        $result2=mysql_query("select * from " . $this->dbtablename . " where " . $this->id_field . " ='$referrer'", $this->dbConnectionID);
        while($row2=mysql_fetch_array($result2, MYSQL_ASSOC))
        {
            $export=array();
            foreach($this->tablefields as $val){
                $export[$val] = $row2[$val];
            }
        }
    }

你在(a)只获得最后一行数据和(b)覆盖第一个数据块的数据(可能需要后者)。

最后,如果你碰到过这个区块(第一次通过你的代码,推荐人不是零):

    else
    {
        $this->getparent($referrer);
    }

你永远不会从递归调用中重新计算一个值,它应该是:

    else
    {
        return $this->getparent($referrer);
    }

我怀疑是实际问题。但我必须质疑这种递归方法是否最好,而不是迭代方法。

答案 1 :(得分:0)

尝试在while循环之前声明$ export