我为 Codeigniter 创建了一个嵌套注释库,它几乎可以工作了。
<ul>
如果不回显每个or<li>
元素,我似乎无法输出嵌套注释。我不希望库直接写任何东西,我想将它保存到一个变量中并返回它,以便我可以在视图中回显它。
这是库代码:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Comments
{
public $parents = array();
public $children = array();
public function init($comments)
{
foreach ($comments as $comment)
{
if ($comment['parent_comment_id'] === NULL)
{
$this->parents[$comment['comment_id']][] = $comment;
}
else
{
$this->children[$comment['parent_comment_id']][] = $comment;
}
}
$this->prepare($this->parents);
} // End of init
public function thread($comments)
{
if(count($comments))
{
echo '<ul>';
foreach($comments as $c)
{
echo "<li>" . $c['text'];
//Rest of what ever you want to do with each row
if (isset($this->children[$c['comment_id']])) {
$this->thread($this->children[$c['comment_id']]);
}
echo "</li>";
}
echo "</ul>";
}
} // End of thread
private function prepare()
{
foreach ($this->parents as $comment)
{
$this->thread($comment);
}
} // End of prepare
} // End of Comments class
上面的代码生成:
- Parent
- Child
- Child Third level
- Second Parent
- Second Child
或在 HTML 中:
<ul>
<li>Parent
<ul>
<li>Child
<ul>
<li>Child Third level</li>
</ul>
</li>
</ul>
</li>
</ul>
<ul>
<li>Second Parent
<ul>
<li>Second Child</li>
</ul>
</li>
</ul>
这是正确的 HTML,但不希望将它们回显出来。
我试图做的是:
public function thread($comments)
{
if(count($comments))
{
$output = '<ul>';
foreach($comments as $c)
{
$output .= "<li>" . $c['text'];
//Rest of what ever you want to do with each row
if (isset($this->children[$c['comment_id']])) {
$this->thread($this->children[$c['comment_id']]);
}
$output .= "</li>";
}
$output .= "</ul>";
echo $output;
}
} // End of thread
这不能按预期工作,并且在回显时会生成以下内容:
- Child Third level
- Child
- Parent
- Second Child
- Second Parent
或 HTML:
<ul><li>Child Third level</li></ul>
<ul><li>Child</li></ul>
<ul><li>Parent</li></ul>
<ul><li>Second Child</li></ul>
<ul><li>Second Parent</li></ul>
这显然是不希望的,因为它没有嵌套评论。
我整天都被困在这上面,有人对我如何正确生成列表有什么建议吗?