手机版

用php实现文章评论系统

时间:2021-08-27 来源:互联网 编辑:宝哥软件园 浏览:

在最近的工作中,我需要完成一个评论功能,我在网上搜索了评论系统的几种显示风格。最后,参考“多说”“畅所欲言”等评论系统,用PHP语言自己实现了一个简单的评论系统。并记录了两种模式(递归模式和非递归模式)的实现过程,分析了两种模式的优缺点,但如何实现前端并未透露。

首先,按如下方式设计数据库:

创建表` comments `(` id ` big int unsigned not null auto _ increment,` arc _ id ` big int unsigned not null comment ' article id ',` user _ id ` big int unsigned not null comment ' user id ',` comment _ id ` big int unsigned not null default ' 0 ' comment '回复一个注释id ',` content ` varchar(255)not null default ` ` comment ' content of comment或reply ',` add _ time ` ` timestamp not null default current _ timestamp comment ',` add time ',` Primary按照以下步骤创建测试数据:

具体实现方案如下(在ThinkPHP框架上实现):

1.递归模式

优点:实现代码简单,如果注释的级别固定在5级,建议使用这个方法,这样前端就可以通过这个数据结果简单实现。

缺点:如果注释的级别不固定,前端将无法显示注释信息,如果级别太多,将消耗大量内存,更糟糕的是,每次递归都要查询数据库,这将大大降低性能。

/* * * $result=array()){ //获取注释列表if(empty($ arc _ id)){ return array();} $ _ where=' arc _ id={ $ arc _ id } AND comment _ id={ $ comm _ id } ';$res=M('注释')-其中($ _ where)-order(' add _ time desc ')-select();if(empty($ RES)){ return array();} foreach($ RES as $ cm){ $ this arr=$ result[];$ cm[' _ child ']=getCommlist($ arc _ id,$cm['id'],$ this arr);$ thisArr=$ cm}返回$ result}一些数据如下所示:

2.非递归模式(堆栈模式实现)

优点:只查询数据库一次,性能更好。可以实现n级评论,前端也能很好的展现

缺点:代码有点复杂,对于固定级别的注释,前端显示注释更复杂。

/* * * } $ RES=M(' comments ')-其中(array(' arc _ id '=$ arc _ id))-order(' add _ time ASC ')-select();$ DataList=$ stack=array();if($ RES){ foreach($ RES as $ k=$ v){//先将注释数据放入仓库(即comment _ id=0)if($ v[' comment _ id ']==0){ $ v[' level ']=0;//设置级别数$ v[' _ root ']=$ v[' id '];//标识注释id array_push($stack,$ v);//堆栈未设置($ RES[$ k]);} } while(!空($ stack)){ $ node=array _ pop($ stack);//堆栈$ DataList[]=$ node;foreach($ RES as $ _ k=$ _ v){ if($ _ v[' comment _ id ']==$ node[' id ']){ $ _ v[' level ']=$ node[' level ']1;//设置级别数$ _ v[' _ root ']=$ node[' _ root '];//标识注释id array_push($stack,$ _ v);//堆栈未设置($ RES[$ _ k]);} } } }返回$ dataList}数据显示效果如下:

以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。

版权声明:用php实现文章评论系统是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。

相关文章推荐