Algorithm To Sort Child Comments

When pulling comments from a database table, it can be very costly when you are performing a query that will automatically sort all of the comments into the parent-child hierarchy. Every extra ms your SQL server spends performing calculations is time that is wasted. If you can easily move this logic to the programming language that you are using it will free up your DB server to serve more data. If you have a blog post that has comments, obtaining the comments from the DB for this post is a simple process, but the problem is that the order of the comments will not be right. If someone replies to the first comment days after lots of other comments have been made, this comment will show up at the end of the list returned from the DB. There are ways in which you can construct your query so that it will return an array of child comments for each comment, but this is way too wasteful. Using a simple recursive method you can sort out the comments using a programming language so as not to lock up your DB server any longer.

A simple SQL query like this is going to pull some comments from a database table that is storing comments for a blog post.

SELECT * FROM Comments WHERE postid=123

This query now leaves you with a list of comments that are a mix of parent and child comments are not in order. This seems a bit messy and can be a daunting problem to solve, but look at how simple that SQL query is. It is worth the effort when your DB server has very little to do to sort the comments. We are going to start this by creating the recursive function. A recursive function is a function that calls itself many times. The following function is written in PHP, but can be easily translated to any other programming languages.

function GetChildren($parentid, $comments)
{
    $childcomments = array();
    foreach($comments as $comment)
    {
                //if the comment has a prent id of 0 then it must be a parent. a parent comment cannot be a child. Also check to see the comment being checked isnt the comment we are getting children for otherwise we will get stuck in an infinite loop
        if($comment['parentid'] != 0 && $comment['parentid'] == $parentid)
        {
            $comment["children"] = GetChildren($comment['id'], $comments);
            $childcomments[] = $comment;
        }
    }
    return $childcomments;
}

 

This function accepts 2 parameters. The parent ID which is the Id of the comment that we want to get the child comments for, and then it contains the full list of all comments that were returned from the database query. When you want to see if a comment has children, you will loop through all of the comments checking to see if any of the comments have a parent ID that is equal to the current comment. Once we find a match we first need to check and make sure that this child comment doesn’t also have child comments,. This is why we use a recursive method. We cant tell how many comments have replies and how deep they go. This way we can do it without needing to know. Once we have checked for more child comments we can add this child comment to an array of child comments for the current comment we are checking.

The only thing left to do now is to determine how to set it off. We need a way to call this method and restart the recursive loop. Here is a completed method that will show you how to pull them from the database and then how to trigger the calling of the recursive loop.

$stmt = $db->prepare("SELECT * FROM Comments WHERE postid=?");
$stmt->execute(array("123"));
$comments = $stmt->fetchAll();

$sortedcomments = array();
foreach($comments as $comment)
{
    if($comment['parentid'] == 0)
    {
        $comment["children"] = GetChildren($comment['id'], $comments);
        $sortedcomments[] = $comment;
    }
}

function GetChildren($parentid, $comments)
{
    $childcomments = array();
    foreach($comments as $comment)
    {
        if($comment['parentid'] != 0 && $comment['parentid'] == $parentid)
        {
            $comment["children"] = GetChildren($comment['id'], $comments);
            $childcomments[] = $comment;
        }
    }
    return $childcomments;
}

 

Related Articles

Related Questions

WordPress Table of Contents Plus Not Working

I have been using this plugin for a while and i really like it. It seems to have completely stopped working recently. I can...

Function Keys Reversing Between Fn Actions And Normal

My keyboard has the usual F1 to F12 keys along the top. I use these for shortcuts in various applications. These keys also have...

Whirlpool Oven F6E6: Appliance Manager 1 Board Communication

I have a brand new Whirlpool oven W11I OM1 4MS2 H or (859991549450). I bought it alongside the microwave combi oven. I have had...

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Latest Tools

List Sorting Tool

Welcome to our innovative list ordering and management tool. This next-level platform enables you to sort a list of items in ascending or descending...

Sudoku Solver

Welcome to our free online Sudoku solving tool, an interactive platform for puzzle enthusiasts seeking a break from a Sudoku conundrum. This advanced platform...

Apply Image Filters To Image

Digital imagery in the modern world is all about reinforcing emotions and stories behind each photo we take. To amplify this storytelling, we are...

Add Watermark To Image

As the world is increasingly consumed by digital media, protecting your original images is paramount. We are thrilled to introduce you to our innovative...

CSV To Xml Converter

Welcome to our CSV to XML converter tool, a convenient and user-friendly solution for all your data conversion needs. This versatile tool on our...

RGB Image Splitter

Welcome to our innovative RGB Splitter - a unique image analyzer tool that offers an in-depth peek into the building blocks of your photos....

Latest Posts

Latest Questions