Phil
Phil

Reputation: 1849

Nested comments code not working

I'm trying to implement code for nested commenting which I found at http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/.

But for some reason I can't get it to work. My result is "Parent Child Child Third level Second Parent Second Child" in one row without any nesting. What am I doing wrong? Is there maybe a setting or extension which I have to enable for this to work? Thanks in advance!

Here's the exact code I'm using:

<?php
class Threaded_comments
{

public $parents  = array();
public $children = array();

/**
 * @param array $comments
 */
function __construct($comments)
{
    foreach ($comments as $comment)
    {
        if ($comment['parent_id'] === NULL)
        {
            $this->parents[$comment['id']][] = $comment;
        }
        else
        {
            $this->children[$comment['parent_id']][] = $comment;
        }
    }
}

/**
 * @param array $comment
 * @param int $depth
 */
private function format_comment($comment, $depth)
{
    for ($depth; $depth > 0; $depth--)
    {
        echo "\t";
    }

    echo $comment['text'];
    echo "\n";
}

/**
 * @param array $comment
 * @param int $depth
 */
private function print_parent($comment, $depth = 0)
{
    foreach ($comment as $c)
    {
        $this->format_comment($c, $depth);

        if (isset($this->children[$c['id']]))
        {
            $this->print_parent($this->children[$c['id']], $depth + 1);
        }
    }
}

public function print_comments()
{
    foreach ($this->parents as $c)
    {
        $this->print_parent($c);
    }
}

}



$comments = array(  array('id'=>1, 'parent_id'=>NULL,   'text'=>'Parent'),
                array('id'=>2, 'parent_id'=>1,      'text'=>'Child'),
                array('id'=>3, 'parent_id'=>2,      'text'=>'Child Third level'),
                array('id'=>4, 'parent_id'=>NULL,   'text'=>'Second Parent'),
                array('id'=>5, 'parent_id'=>4,   'text'=>'Second Child')
            );

$threaded_comments = new Threaded_comments($comments);

$threaded_comments->print_comments();

?>

Upvotes: 2

Views: 208

Answers (1)

Oussama Jilal
Oussama Jilal

Reputation: 7739

I think you will only see the formating in a console, not if use it in a web page. if you want it in a web page you must replace the \n and \t in the following function with <br/> and &nbsp;&nbsp;&nbsp;&nbsp; respectively.

/**
 * @param array $comment
 * @param int $depth
 */
private function format_comment($comment, $depth)
{
    for ($depth; $depth > 0; $depth--)
    {
        echo "\t";
    }

    echo $comment['text'];
    echo "\n";
}

should become :

/**
 * @param array $comment
 * @param int $depth
 */
private function format_comment($comment, $depth)
{
    for ($depth; $depth > 0; $depth--)
    {
        echo "&nbsp;&nbsp;&nbsp;&nbsp;";
    }

    echo $comment['text'];
    echo "<br />";
}

Upvotes: 2

Related Questions