php實現(xiàn)文章評論系統(tǒng)
最近工作中需要完成一個評論的功能,上網(wǎng)查找了幾個評論系統(tǒng)的展示樣式。最后參考“多說”和“暢言”等評論系統(tǒng),自己使用PHP語言實現(xiàn)了一個簡單的評論系統(tǒng)。并記錄了兩種方式(遞歸方式和非遞歸方式)的實現(xiàn)過程,以及分析兩種方式的優(yōu)缺點,但前端如何實現(xiàn)就沒有展現(xiàn)了。
首先設計數(shù)據(jù)庫如下:
create table `comments`( `id` bigint unsigned not null AUTO_INCREMENT, `arc_id` bigint unsigned not null COMMENT '文章id', `user_id` bigint unsigned not null COMMENT '用戶id', `comment_id` bigint unsigned not null DEFAULT '0' COMMENT '回復某個評論的id', `content` varchar(255) not null DEFAULT '' COMMENT '評論或回復的內(nèi)容', `add_time` timestamp not null DEFAULT CURRENT_TIMESTAMP COMMENT '添加時間', PRIMARY KEY (`id`), KEY `arc_id` (`arc_id`) )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '文章評論表';
創(chuàng)建測試數(shù)據(jù)如下:
具體實現(xiàn)方案如下(在ThinkPHP框架上實現(xiàn)):
1、遞歸方式
優(yōu)點:實現(xiàn)代碼簡單,而且如果評論的層級固定在5個層次一下的話,建議使用該種方法,這樣前端通過這種數(shù)據(jù)結(jié)果實現(xiàn)簡單。
缺點:如果評論的層級沒有固定的話,前端將無法展示評論信息了,而且如果層級太多的話,將會極大的消耗內(nèi)存,更要命的是每次遞歸都得查詢數(shù)據(jù)庫,性能將大大的降低。
/** * @param $arc_id 文章id * @param int $comm_id 評論id * @param array $result * @return array */ function getCommlist($arc_id, $comm_id = 0, &$result = array()){ //獲取評論列表 if(empty($arc_id)){ return array(); } $_where = "arc_id = {$arc_id} AND comment_id = {$comm_id}"; $res = M('comments')->where($_where)->order('add_time DESC')->select(); if(empty($res)){ return array(); } foreach ($res as $cm) { $thisArr = &$result[]; $cm["_child"] = getCommlist($arc_id,$cm['id'],$thisArr); $thisArr = $cm; } return $result; }
部分數(shù)據(jù)展示如下:
2、非遞歸方式(堆棧方式實現(xiàn))
優(yōu)點:只查詢一次數(shù)據(jù)庫,性能較好??梢詫崿F(xiàn)n層級的評論,前端也能很好的展示
缺點:代碼稍微復雜,對于固定的層級評論,前端展示評論較為復雜。
/** * @param $arc_id 文章id * @return array */ public function getCommlist($arc_id){ if(empty($arc_id)){ return array(); } $res = M('comments')->where(array('arc_id'=>$arc_id))->order('add_time ASC')->select(); $dataList = $stack = array(); if($res){ foreach($res AS $k=>$v){ //先將評論的數(shù)據(jù)進行入庫(即comment_id=0) if($v['comment_id'] == 0){ $v['_level'] = 0; //設置層級數(shù) $v['_root'] = $v['id']; //標識評論id array_push($stack,$v); //入棧 unset($res[$k]); } } while(!empty($stack)){ $node = array_pop($stack); //出棧 $dataList[] = $node; foreach($res as $_k=>$_v){ if($_v['comment_id'] == $node['id']){ $_v['_level'] = $node['_level']+1; //設置層級數(shù) $_v['_root'] = $node['_root']; //標識評論id array_push($stack,$_v); //入棧 unset($res[$_k]); } } } } return $dataList; }
數(shù)據(jù)展示效果如下:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
windows7下php開發(fā)環(huán)境搭建圖文教程
這篇文章主要介紹了windows7下php開發(fā)環(huán)境搭建的圖文教程,非常的詳盡,有需要的小伙伴快來參考下吧。2015-01-01php根據(jù)數(shù)據(jù)id自動生成編號的實現(xiàn)方法
下面小編就為大家?guī)硪黄猵hp根據(jù)數(shù)據(jù)id自動生成編號的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10PHP配置把錯誤日志以郵件方式發(fā)送方法(Windows系統(tǒng))
這篇文章主要介紹了PHP配置把錯誤日志以郵件方式發(fā)送方法(Windows系統(tǒng)),本文給出了配置示例和使用例子,需要的朋友可以參考下2015-06-06PHP+jQuery+Ajax實現(xiàn)分頁效果 jPaginate插件的應用
這篇文章主要介紹了PHP+jQuery+Ajax實現(xiàn)分頁效果,以及jPaginate插件的應用2015-10-10