php實(shí)現(xiàn)無(wú)限級(jí)評(píng)論功能
來(lái)源:涼官灰
發(fā)布時(shí)間:2020-05-06 13:31:33
閱讀量:1006
php實(shí)現(xiàn)評(píng)論無(wú)限級(jí)方法
1、首先在評(píng)論表中加入一個(gè)存放父級(jí)評(píng)論ID的字段,其默認(rèn)值為0,當(dāng)父級(jí)ID為0是就頂級(jí)分類。
SQL:
1 2 3 4 5 6 7 8 | 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、再創(chuàng)建一個(gè)遞歸函數(shù),將評(píng)論數(shù)據(jù)轉(zhuǎn)換成樹(shù)形結(jié)構(gòu);
PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ;
}
|
返回出來(lái)的數(shù)據(jù)結(jié)構(gòu)如下:
1 2 3 4 5 6 7 8 9 10 | [
'一級(jí)評(píng)論' ,
'childs' => [
'二級(jí)評(píng)論'
'childs' => [
'....'
]
]
]
|
3、最后將轉(zhuǎn)換后的評(píng)論數(shù)據(jù),循環(huán)展示出來(lái)即可。