gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:33:05 33 4
gpt4 key购买 nike

对不起,如果标题令人困惑,但我正在尝试使用递归函数获取所有评论及其回复。问题是顶级评论对象与评论具有不同的数据结构。顶级评论来自 $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 块来分隔不同的结构?

最佳答案

我只会有 get_comments() 的默认值如 NULL ,然后检查它是否为空;如果是,请使用顶部评论。您不希望传递的评论为 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 中的一个例子做到了。请注意文档中的此评论:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

关于php - 参数数据结构变化时的递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342713/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com