首页 > 编程 > PHP > 正文

php无限级评论嵌套实现代码php技巧

2020-03-22 17:04:26
字体:
来源:转载
供稿:网友
本文讲的是php无限级评论嵌套实例介绍, 我在设计BB的过程中,也一直在思考是否可以不通过递归来实现无限级分类的结构展现和父子结构查找,因为如果不对这里的算法进行优化后果可能是致命的

我在设计BB的过程中,也一直在思考是否可以不通过递归来实现无限级分类的结构展现和父子结构查找,因为如果不对这里的算法进行优化后果可能是致命的!试想一下,一篇文章如果评论数为300,按正常的递归算法,至少就得查询数据库301次,而且还是在没有任何嵌套的情况下,如果有过一两级嵌套或者评论数过1000,那数据库不是直接宕掉?
而实际上,PHP强大的数组处理能力已经能帮助我们快速方便的解决这个问题。下图为一个无限级分类的

数据库结构:

IDparentID newsID commts
108文章ID为8的评论
21 8对ID为1的评论的回复
328对ID为2的评论的回复

要在前台嵌套式的展现文章编号8的评论,其实我们只用查询一次数据库,即“SELECT * FROM TABLE WHERE newsID=8”,而把后期的递归工作交给强大的PHP数组来完成。这里可能涉及的问题就是数组的结构关系的重组,即将所有停留在一级分类上的评论全部放到自己的parentID下,形成children项。
下面将BBComment类中这块的代码粘贴出来,希望与大家分享下我的思路,也希望大家能够提出更好更有效率的算法。

方法一

/**  * 按ID条件从评论数组中递归查找 function getCommentsFromAryById($commtAry, $id)  if ( !is_array($commtAry) ) return FALSE;  foreach($commtAry as $key= $html' target='_blank'>value) {  if ( $value[ id ] == $id ) return $value;  if ( isset($value[ children ]) is_array($children) ) $this- getCommentsFormAryById($value[ children ], $id);  * 追加 子评论 到 主评论 中,并形成children子项  * @param array $commtAry 原评论数据引用  * @param int $parentId 主评论ID  * @param array $childrenAry 子评论的值 function addChildenToCommentsAry($commtAry, $parentId, $childrenAry)  if ( !is_array($commtAry) ) return FALSE;  foreach($commtAry as $key= $value) {  if ( $value[ id ] == $parentId ) {  $commtAry[$key][ children ][] = $childrenAry;  return TRUE;  if ( isset($value[ children ]) ) $this- addChildenToCommentsAry($commtAry[$key][ children ], $parentId, $childrenAry);  $result = $this- BBDM- select($table, $column, $condition, 0, 1000);  /* 开始进行嵌套评论结构重组 */  array_shift($result);  $count = count($result);  $i = 0;  while( $i $count ) {  if ( 0 != $result[$i][ parentId ] ) {  $this- addChildenToCommentsAry($result, $result[$i][ parentId ], $result[$i]);  unset($result[$i]);  $i++;  $result = array_values($result);  /* 重组结束 */

实现方法二

核心代码摘自WordPress

 ?php$comments = array ( array ( id = 3 , parent = 0  array ( id = 9 , parent = 0  array ( id = 1 , parent = 3  array ( id = 2 , parent = 3  array ( id = 5 , parent = 1  array ( id = 7 , parent = 1 function html5_comment($comment) { echo li  echo id: , $comment[ id ], parent: , $comment[ parent function start_el( $output, $comment) { ob_start(); html5_comment($comment); $output .= ob_get_clean();function end_el( $output) { $output .= /li !-- #comment-## -- /n function start_lvl( $output) { $output .= ol >

这篇文章就介绍到这了,其实大家多参考一些开源的cms也可以看到很多不错的代码,希望大家以后多多支持php 。

相关推荐:

PHP实现数据库的增删查改功能及完整代码php实例

PHPMAILER实现PHP发邮件功能php实例

php-app开发接口加密详解_php技巧


以上就是php无限级评论嵌套实现代码php技巧的详细内容,PHP教程

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表