Home > Article > Backend Development > 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 ;
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; }
returned The data structure is as follows:
[ '一级评论', 'childs' => [ '二级评论' 'childs' => [ '....' ] ] ]
3. Finally, the converted comment data can be displayed in a loop.
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!