2

我正在尝试实现我在http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/找到的嵌套评论代码。

但由于某种原因,我无法让它工作。我的结果是一行中的“父子子子第三级第二父子第二子”,没有任何嵌套。我究竟做错了什么?是否有我必须启用的设置或扩展才能使其正常工作?提前致谢!

这是我正在使用的确切代码:

<?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();

?>
4

1 回答 1

2

我认为您只会在控制台中看到格式,而不是在网页中使用它。如果您想在网页中使用它,则必须将以下函数中的and分别替换为\nand 。\t<br/>&nbsp;&nbsp;&nbsp;&nbsp;

/**
 * @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 format_comment($comment, $depth)
{
    for ($depth; $depth > 0; $depth--)
    {
        echo "&nbsp;&nbsp;&nbsp;&nbsp;";
    }

    echo $comment['text'];
    echo "<br />";
}
于 2012-08-07T19:29:58.623 回答