doutuan8887
doutuan8887
2015-04-29 18:49

从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 douyan2680 6年前

    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...

    点赞 评论 复制链接分享

相关推荐