开发者

Recursive PHP function is not returning a result [duplicate]

This question already has answers here: How to use return inside a recursive function in PHP (4 answers) Closed 9 months ago.

Here is my function:

function loop($id) {

    unset($result, $sql, $query);
    $sql = " SELECT parent_id FROM page_entries WHERE id = '$id' ";
    $query = mysql_query($sql) or die(mysql_error());
    $result = mysql_fetch_assoc($query) or die(mysql_error());

    if ($result['parent_id'] != 0) {
        echo $result['parent_id'] . "... looping<br>";
        loop($result['parent_id']);
    } else {
        echo $result['parent_id'] . "... done loop";
        return $result['parent_id'];
    }
}

echo loop('2');

I'm echoing the parent_id for testing. This is what is output to the browser:

1... looping

0... done loop

Where I'm not sure: the echo loop('2') doesn't echo anything from return $result['id'] if I comment out the 开发者_如何转开发echo lines in the function. I've tried testing by changing the return to return 'foo'; and still nothing.

How can I fix it?


At a glance, I think

loop($result['parent_id']);

should be

return loop($result['parent_id']);

otherwise your if branch is returning nothing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜