doutuan8887 2015-04-29 18:49
浏览 50
已采纳

从PHP中的另一个函数调用递归函数

I have created a recursive function which returns the array value. So I am calling that function from another function. but it doesn't return any values. The function is given below,

public function sitemapAction() {
    $sites = self::getNavigation();
    foreach(self::recursiveSitemap($sites) as $url) {
    ...
    ...
    }
}

public function recursiveSitemap($sites)
{
    $result = array();
    foreach ($sites as $site) {
        $result[]= array($site['DFA']);
        if (is_array($site['items'])) {
            return recursiveSitemap($site['items']);
        }
    }
}

Please help me on this.

  • 写回答

1条回答 默认 最新

  • douyan2680 2015-04-29 18:54
    关注

    If you look carefully at your recursive method, you will see that it actually does not return anything at all:

    public function recursiveSitemap($sites)
    {
        $result = array();
        foreach ($sites as $site) {
            $result[]= array($site['DFA']);
            if (is_array($site['items'])) {
                return recursiveSitemap($site['items']);
            }
        }
    }
    

    If your variable $site['items'] is an array you call your method again, going deeper, without doing anything with the returned value.

    And if not?

    It would seem you would need to add the result you get back from your recursive function call to your $result array and return that, but I don't know exactly what output you expect.

    Apart from that you have a small typo, you need self::recursiveSitemap($site['items']) if you want to call the same method recursively.

    A simple example:

    public function recursiveSitemap($sites)
    {
        $result = array();
        foreach ($sites as $site) {
            if (is_array($site['items'])) {
                // do something with the result you get back
                $result[] = self::recursiveSitemap($site['items']);
            } else {
                // not an array, this is the result you need?
                $result[]= array($site['DFA']);
            }
        }
        // return your result
        return $result;
    }
    

    Assuming that $result is the thing you want to get back...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?