我正在尝试实现我在 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/>
和
分别。
/**
* @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 " ";
}
echo $comment['text'];
echo "<br />";
}
关于php - 嵌套注释代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852666/