代码之家  ›  专栏  ›  技术社区  ›  pdizz

参数的数据结构变化时的递归函数?

  •  2
  • pdizz  · 技术社区  · 13 年前

    如果标题令人困惑,我很抱歉,但我正在尝试用递归函数获取所有评论及其回复。问题是顶级注释对象的数据结构与注释不同。顶级评论可从 $comment_object->data->children 而所有评论回复都是从 $comment->data->replies 。这就是我目前为止所掌握的:

    public function get_top_comments()
    {
        $comments_object = json_decode(file_get_contents("http://www.reddit.com/comments/$this->id.json"));
        sleep(2); // after every page request
    
        $top_comments = array();
        foreach ($comments_object[1]->data->children as $comment)
        {
            $c = new Comment($comment->data);
            $top_comments[] = $c;
        }
        return $top_comments;
    }
    
    public function get_comments($comments = $this->get_top_comments) //<-- doesn't work
    {
        //var_dump($comments);
    
        foreach ($comments as $comment)
        {
            if ($comment->data->replies != '')
            {
                //Recursive call
            }
        }
    }
    

    我试着分配 $comments = $this->get_top_comments 作为递归函数的默认参数,但我猜PHP不支持这个?我是否必须在函数中使用if-else块来分隔不同的结构?

    1 回复  |  直到 13 年前
        1
  •  3
  •   Cat    13 年前

    我只需要默认值 get_comments() NULL ,然后检查它是否为空;如果是,请使用顶部注释。你不希望传递的评论是 无效 无论如何

    public function get_comments($comments = NULL)
    {
        //var_dump($comments);
    
        if (is_null($comments))
            $comments = $this->get_top_comments;
    
        foreach ($comments as $comment)
        {
            if ($comment->data->replies != '')
            {
                //Recursive call
            }
        }
    }
    

    下面是一个例子 the PHP docs 请注意文档中的注释:

    默认值必须是常量表达式,而不是(例如)变量、类成员或函数调用。