Sorry if the title is confusing but I’m trying to get all comments and their replies with a recursive function. The problem is the top-level comment object has a different data structure than the comments. The top-level comments are accessed from $comment_object->data->children while all comment replies are accessed from $comment->data->replies. This is what I have so far:
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
}
}
}
I tried to assign $comments = $this->get_top_comments as the default parameter of the recursive function but I guess PHP doesn’t support this? Do I have to use an if-else block within the function to separate the different structures?
I would just have the default value of
get_comments()asNULL, then check if it’s null; if it is, use the top comments. You don’t want the comments passed to beNULLanyway.This is how one example in the PHP docs does it. Note this comment in the docs: