我有这个功能:
function show_comments(&$comments, $parent_id = 0 ) {
$comments_list = "";
$i = 0;
foreach($comments as $comment) :
if ($comment["parent_id"] != $parent_id)
continue;
$comments_list .= '<div class="comment level-'. $i . '">';
$i++;
$comments_list .= "<p>$comment[body]</p>";
$comments_list .= $this->show_comments($comments, $comment['id_comment']);
$comments_list .= '</div>';
endforeach;
return $comments_list;
}
我希望父级div的课程 level-0 且该家长的直接孩子有 1级和级别的孩子的孩子 - 1 有 level-2 等级,依此类推。我怎么能这样做?
答案 0 :(得分:4)
// add a new parameter --------------------------------
// |
function show_comments(&$comments, $parent_id = 0, $level = 0) {
$comments_list = "";
// not needed
// $i = 0;
foreach($comments as $comment) :
if ($comment["parent_id"] != $parent_id)
continue;
// use the level parameter ------------------------
// |
$comments_list .= '<div class="comment level-'. $level . '">';
// not needed
// $i++;
$comments_list .= "<p>$comment[body]</p>";
// increment it on recursive calls -----------------------------------------
// |
$comments_list .= $this->show_comments($comments, $comment['id_comment'], $level + 1);
$comments_list .= '</div>';
endforeach;
return $comments_list;
}