使用Laravel的PHP注释系统 [英] PHP Comment System using Laravel

查看:49
本文介绍了使用Laravel的PHP注释系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel PHP开发网站,并尝试使用以下结构创建评论系统:

I am developing a website using laravel PHP and trying to do a comment system using the following structure:

- Comment 1 (id = 1)
 -- Reply 1 (id = 2) (parent_id = 1)
  --- Reply 2.1 (id = 3) (parent_id = 2)
 -- Reply 2 (id = 4) (parent_id = 1)

我想知道如何做一个foreach来解决这个问题?由于我不知道一个评论会有多少个孩子评论.

I am wondering how would I do a foreach to cover that? Since i don't know how many child comments a comment will have.

推荐答案

Table Like:

+------------+-----------+---------+
| comment_id | parent_id | comment |
+------------+-----------+---------+
|          1 |         0 | test    |
|          2 |         1 | test1   |
|          3 |         0 | test2   |
|          4 |         0 | test3   |
|          5 |         1 | test4   |
|          6 |         2 | test4   |
|          7 |         4 | test5   |
|          8 |         5 | test6   |
|          9 |         6 | test7   |
|         10 |         4 | test8   |
|         11 |         3 | test9   |
+------------+-----------+---------+


Get first level parent:

$comments = Comment::where('parent_id', '0')->orderBy('comment_id', 'asc')->get();

$result = array();
foreach($comments as $comment){
    $list = array();
    $list = array_merge($list, [['comment_id' => $comment->comment_id, 'parent_id' => $comment->parent_id, 'comment' => $comment->comment]]);
    $result = array_merge($result, $this->get_child_comment($comment->comment_id,0, $list));
}


function get_child_comment($pid,$level,$list=array()) {
        $sub_comments = Comment::where('parent_id','=',$pid)->where('comment_id','!=',$pid)->orderBy('comment_id', 'asc')->get();        
        foreach($sub_comments as $sub_comment){
            $space=" "; sigm='-';
            for($j=0; $j<=$level; $j++)
            {
                $space .=$space;
            }
            for($j=0; $j<=$level; $j++)
            {
                $space .= $sigm;
            }
            $sub_comment->comment = html_entity_decode($space, ENT_QUOTES, "utf-8").' '.$sub_comment->comment;

            $list = array_merge($list, array(['comment_id' => $sub_comment->comment_id, 'parent_id' => $sub_comment->parent_id, 'comment' => $sub_comment->comment]));

            $list = $this->get_child_comment($sub_comment->comment_id, $level+1, $list);
        }
       return $list;
    }
}


return get array.simple print using foreach:
foreach($result as $val) {
    echo $val['comment'].'<br>';
}

Output:

test

  - test1

    -- test4

        --- test7

  - test4

    -- test6

test2

  - test9

test3

  - test5

  - test8

这篇关于使用Laravel的PHP注释系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆