doucheng5705 2015-04-07 17:57
浏览 60

递归PHP函数不返回结果

Just a simple function to build breadcrumbs based off a simple database table where there are columns:

id, parent, title

The "parent" column can be 0 for top-level, or the "id" of another row for sub-categories (unlimited depth). All I'm trying to do is have a function that'll help me build breadcrumbs from it, starting from the "id" of the bottom-most category I specify and working its way up to the top parent. Here's what I have:

    function getCategoryParents($id=0, $out=array()) {
        $id = (int)$id;
        if ($id > 0) {
            $query = "SELECT * FROM `" .$this->tables['categories']. "` WHERE (`id`=" .$id. ")";
            $cat = sqlfetch(sqlquery($query));
            array_push($out, $cat);
            if ($cat['parent']) {
                $this->getCategoryParents($cat['parent'], $out);
            } else {
                return $out;
            }
        } else {
            return $out;
        }
    }

But it's not returning anything. But, if I do a print_r($out) from within the function instead of return, ex:

            if ($cat['parent']) {
                $this->getCategoryParents($cat['parent'], $out);
            } else {
                echo print_r($out);
            }

It outputs the array just fine. But I need to be able to actually work with the array, so I need it returned from the function. I'm sure I'm missing something incredibly small, but I cannot figure it out for the life of me!

Also, I don't want to do a global variable, and also need the info of the category id specified in the initial function call as part of the array as well (as I was trying to do).

  • 写回答

1条回答 默认 最新

  • dopq87915 2015-04-07 19:20
    关注

    Following the suggestions, here's what ended up working:

        function getCategoryParents($id=0) {
            $out = array();
            $id = (int)$id;
            if ($id > 0) {
                $query = "SELECT * FROM `" .$this->tables['categories']. "` WHERE (`id`=" .$id. ")";
                $cat = sqlfetch(sqlquery($query));
                array_push($out, $cat);
                if ($cat['parent']) {
                    $out = array_merge($out, $this->getCategoryParents($cat['parent']));
                }
            }
            return $out;
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画