0

I have nested replies like the following:

comment
-reply1
--reply3
---reply4
----reply5
-reply2
--reply6

I have this function in my model

return $this->hasMany(self::class, 'parentid', 'postid')
        ->visible()
        ->with('replies');

and I wrote this code to get all replies

 foreach($replies as $reply){
        if(!empty($reply->replies)){
            foreach($reply->replies as $re){
                $replies->push($re);
            }
        }
    }

  return $replies;

this code can get the following replies:{reply1,reply2,reply3,reply6} How can I retrieve all the replies even if there are deeper replies without using recursion???

  • Why don't you want to use recursion? It seems like the obvious choice for this... – Zeth Dec 29 '21 at 08:25
  • recursion is very slow and needs a lot of memory, I'm working with billion of comments and replies so I need a perfect solution. @Zeth – NohaMahgoub Dec 29 '21 at 08:41

1 Answers1

0

You can use Queue instead of recursion.

  1. Push all your replies to queue.
  2. Dequeue a reply from the queue.
  3. If there are deeper replies from it, then you push deeper replies in the queue.
  4. You repeat step 2 and step 3. Until the queue is empty.

Edit: I am not familiar with php, but it should tell you how to use queue.

$queue = $replies;
$allReplies = array();
while($queue) {
    $reply = array_shift($queue);
    $allReplies[] = $reply;
    if(!empty($reply->replies)){
        foreach($reply->replies as $re){
            $queue[] = $re;
        }
    }
}
Changsong Li
  • 143
  • 6
  • but I don't know exactly how many nested replies I have! – NohaMahgoub Dec 29 '21 at 08:43
  • can you write the code because I'm not sure if I get you? – NohaMahgoub Dec 29 '21 at 08:46
  • @NohaMahgoub You don't need to know how many nested replies you have. Every time you find a deeper reply, you will push the deeper reply to the queue again. And it will be dequeue again and check whether it has deeper reply. Eventually you will reach every reply. You can read through this link. Queue is better than deep recursion. [link](https://stackoverflow.com/questions/11278010/php-is-the-there-a-safe-way-to-perform-deep-recursion) – Changsong Li Dec 29 '21 at 08:54
  • @NohaMahgoub I update a demo for you. – Changsong Li Dec 29 '21 at 09:09