0

I have this function:

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;
}

I want for the parent div to have class level-0 and the direct child of that parent have level-1 and child of child with level-1 to have class level-2 and so on. How can I do this?

1
  • You will have to loop through all the comments to build a tree. Or you can keep track of the level_id in the database. Commented Jul 2, 2014 at 9:39

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.