php – 如何实现嵌套注释?
作者:互联网
我想在我的网站上发表评论,如下所示:
<li>Parent
<ul>
<li>child one</li>
<li>child two
<ul>
<li>grandchild</li>
<li>other grandchild</li>
</ul>
</li>
</ul>
<li>Another parent with no children</li>
<li>
我已阅读the following article,但它不使用< li>.那么有没有办法像我之前用数组那样显示评论?谢谢.
$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')
);
解决方法:
我认为你的评论表有id,parent_id,comment,……我的建议是这样的;
选择你的评论;
$sql = "SELECT *FROM comments ORDER BY id DESC";
$rows = mysql_query($sql);
下一步是数组操作.您可以在下面看到以下代码并尝试使用demo here;
$rows = your_select_result;//I assumed that you have done these stuffs
$comments = $row;
/**
This is test data, please remove this array while you are
running own application.Since you will use the data one you get your db
**/
$comments = array(
1 => array('id' => 1, 'parent_id' => 0, 'childs' => array()),
2 => array('id' => 2, 'parent_id' => 0, 'childs' => array()),
3 => array('id' => 3, 'parent_id' => 0, 'childs' => array()),
5 => array('id' => 5, 'parent_id' => 0, 'childs' => array()),
11 => array('id' => 11, 'parent_id' => 0, 'childs' => array()),
17 => array('id' => 17, 'parent_id' => 0, 'childs' => array()),
23 => array('id' => 23, 'parent_id' => 0, 'childs' => array()),
28 => array('id' => 28, 'parent_id' => 0, 'childs' => array()),
4 => array('id' => 4, 'parent_id' => 1, 'childs' => array()),
6 => array('id' => 6, 'parent_id' => 1, 'childs' => array()),
8 => array('id' => 8, 'parent_id' => 2, 'childs' => array()),
9 => array('id' => 9, 'parent_id' => 2, 'childs' => array()),
7 => array('id' => 7, 'parent_id' => 3, 'childs' => array()),
12 => array('id' =>12, 'parent_id' => 7, 'childs' => array()),
13 => array('id' => 13, 'parent_id' => 12, 'childs' => array()),
);
/** Comment prepare start */
foreach ($comments as $k => &$v) {
if ($v['parent_id'] != 0) {
$comments[$v['parent_id']]['childs'][] =& $v;
}
}
unset($v);
foreach ($comments as $k => $v) {
if ($v['parent_id'] != 0) {
unset($comments[$k]);
}
}
/** Comment prepare end */
//Your indent pattern
function indent($size) {
$string = "";
for ($i = 0; $i < $size; $i++) {
$string .= "#";
}
echo $string;
}
function printComments($comments, $indent = 0) {
foreach ($comments as $comment) {
echo indent($indent + 1).' I am comment '.$comment['id']."\n";
if (!empty($comment['childs'])) {
printComments($comment['childs'], $indent + 1);
}
}
}
printComments($comments);
有关演示,请参阅here
标签:html,php,html-lists 来源: https://codeday.me/bug/20190902/1789274.html