1

我找到了一个类的预先编写的脚本来创建线程注释,但是在尝试实现它之后,什么也没有打印出来。数组 si 保存数据,我已经确认,但是调用函数时不会打印任何内容,所以我想知道是否有人可以帮忙。

该脚本可以在这里找到:

也如下:

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);
        }
    }

}

我在 Germannrumm 的帮助下使用的代码如下:

$q = $DBH->prepare("SELECT id, parent_id, comment FROM comments WHERE page = ?");
$q->bind_param("i", $page);
$q->execute();

$q->bind_result($id, $parent_id, $text);

$all_results = array();

while ($q->fetch()) {
    $all_results[] = array(
        'id' => $id, 
        'parent_id' => $parent_id, 
        'text' => $text);
}
$q->close();

任何帮助是极大的赞赏!谢谢!

$tc = new Threaded_comments($all_results);
$tc->print_comments();
4

1 回答 1

2

该类工作正常,但我们无法为您测试您的数据库代码。确保您确实将数组传递给类。在你开始上课之前做一个 var_dump($all_results) 。

于 2011-01-13T03:56:39.210 回答