Home > Backend Development > PHP Tutorial > PHP implements unlimited comment function

PHP implements unlimited comment function

Guanhui
Release: 2023-04-08 16:04:02
Original
5365 people have browsed it

PHP implements unlimited comment function

php method to implement unlimited comments

1. First, add a field to store the parent comment ID in the comment table, its default value is 0, when the parent ID is 0, it is the top category.

SQL:

CREATE TABLE comment (
    comm_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    user_id INT UNSIGNED NOT NULL DEFAULT 0 ,
    parent_id INT UNSIGNED NOT NULL DEFAULT 0 ,
    article_id INT UNSIGNED NOT NULL DEFAULT 0 ,
    comm_cont TEXT,
    comm_time INT UNSIGNED NOT NULL DEFAULT 0 
) ENGINE=MYISAM CHARSET=UTF8 ;
Copy after login

2. Create a recursive function to convert the comment data into a tree structure;

PHP:

function get_childs_comment($comments, $parent_id = 0, $level = 0)
{
    $new_comments = [];

    foreach ($comments as $key => $val) {
        if ($val['pid'] == $parent_id) {
            $val['level'] = $level;
            $val['childs'] = get_childs_comment($comments, $val['id'], $level + 1);
            $new_comments[] = $val;
        }
    }

    return $new_comments;
}
Copy after login

returned The data structure is as follows:

[
    '一级评论',
    'childs' => [
        '二级评论'
        'childs' => [
            '....'
        ]
    ]

]
Copy after login

3. Finally, the converted comment data can be displayed in a loop.

PHP implements unlimited comment function

The above is the detailed content of PHP implements unlimited comment function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template