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

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

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题