How can a more streamlined approach be implemented to handle the retrieval and display of comments and subcomments in PHP?

When handling comments and subcomments in PHP, a more streamlined approach can be implemented by using a recursive function to retrieve and display nested comments. This function can iterate through each comment and its subcomments, displaying them in a hierarchical structure. By using recursion, the code can handle an unlimited depth of nested comments efficiently.

// Recursive function to display comments and subcomments
function displayComments($comments, $parent_id = 0, $level = 0) {
    foreach ($comments as $comment) {
        if ($comment['parent_id'] == $parent_id) {
            echo str_repeat('-', $level) . $comment['text'] . "<br>";
            displayComments($comments, $comment['id'], $level + 1);
        }
    }
}

// Example usage
$comments = [
    ['id' => 1, 'parent_id' => 0, 'text' => 'Comment 1'],
    ['id' => 2, 'parent_id' => 0, 'text' => 'Comment 2'],
    ['id' => 3, 'parent_id' => 1, 'text' => 'Subcomment 1'],
    ['id' => 4, 'parent_id' => 1, 'text' => 'Subcomment 2'],
    ['id' => 5, 'parent_id' => 3, 'text' => 'Sub-subcomment 1'],
];

displayComments($comments);