php - 嵌套注释代码不起作用

标签 php

我正在尝试实现我在 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();

?>

最佳答案

我认为您只会在控制台中看到格式,而不会在网页中使用它。如果您想在网页中使用它,则必须替换 \n\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 />";
}

关于php - 嵌套注释代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852666/

相关文章:

PHPStorm - 找不到内部对象的方法

php - 在一台服务器中重定向 2 个域的问题

php - 如何在 IIS 上同时运行多个版本的 PHP

php - 如何合并 mysql 中的所有表?

javascript - 谷歌图表 mysql PHP

php - 如何在服务器上安全地存储文件

php - PHP 变量大小有限制吗?

php - 使用 mysql 建立 php 错误数据库的最佳方法?

php - 用 <p> 标签替换换行符

php - 电子商务商店/Neast属性的 Elasticsearch 存储桶列表