我为Codeigniter创建了一个嵌套的注释库,它的几乎正在工作。
我似乎无法在不回显每个<ul>
或<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
这不能按预期工作,并在echo'd:
时生成以下内容- 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>
这显然不是理想的,因为它没有嵌套评论。
我整天都被困在这一天,有人建议我如何才能正确生成列表?
答案 0 :(得分:1)
试试这个:
public function thread($comments,$output='')
{
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']])) {
$output.=$this->thread($this->children[$c['comment_id']],$output);
}
$output .= "</li>";
}
$output .= "</ul>";
return $output;
}
}
我还没有测试过,但它看起来应该有效!
答案 1 :(得分:0)
问题是,在递归调用完成之前,您没有回显一个级别的输出,因为您正在将内容累积到$output
变量中。而不是容纳它,只是在那一刻回应它:
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