我在设计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=>$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 if ( '0' != $result[$i]['parentid'] ) {
$this->addchildentocommentsary($result, $result[$i]['parentid'], $result[$i]);
unset($result[$i]);
}
$i++;
}
$result = array_values($result);
/* 重组结束 */
