PHP - 递归函数的增量

时间:2014-07-02 09:32:30

标签: php codeigniter

我有这个功能:

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 等级,依此类推。我怎么能这样做?

1 个答案:

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