I created a nested comment library for Codeigniter and it’s almost working.
I can’t seem to output the nested comments without echoing each <ul> or <li> element. I don’t want the library writing anything directly, I want to save it to a variable and return it so that I can echo it out inside a view.
Here is the library code:
<?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
The above code generates:
- Parent
- Child
- Child Third level
- Second Parent
- Second Child
or in 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>
This is the correct HTML, but echoing them out is not desirable.
What I tried to do was:
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
This doesn’t work as expected and it generates the following when echo’d:
- Child Third level
- Child
- Parent
- Second Child
- Second Parent
or the 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>
This is obviously not desired since it’s not nesting the comments.
I’ve been stuck on this all day, anyone have a suggestion on how I can get the list to be generated properly?
Try this:
I haven’t tested it, but it looks like it should work!