ThinkPHP结合Jquery实现无限级嵌套回复
blog程序出来这么久,一直为文章的嵌套回复困恼。主要由于ThinkPHP模板的缘故,无法使用PHP语言在页面直接生成嵌套内容。经过不断的度娘爬文,找到了个思路。
思路大概是,先从数据库中读取文章的所有回复,在ThinkPHP中对数组计算,形成一个树形结构。
以下是数据库结构:

每一条记录通过reply字段,跟他的父项目建立关联。使用递归的方法将子项加入父项目,直到最底层介绍,重新整理后通过JSON输出整个回复的树形结构。
以下为ThinkPHP处理回复的函数
/*返回经过处理过后Json,完成回复嵌套*/
public function findParentNode($array, $children, $parentId) {
$length = sizeof($array);
for ($i = 0; $i < $length; $i++) {
if ($array[$i]['id'] == $parentId) {
if ($array[$i]['children'] == NULL) {
$array[$i]['children'] = array($children);
//给每个有子项的父项加入一个children字段
} else {
array_push($array[$i]['children'], $children);
}
return $array;
}
if (!empty($array)) {
$array[$i]['children'] = $this->findParentNode($array[$i]['children'], $children, $parentId);
//递归调用往下一层级遍历
}
}
return $array;
}
/*$id:文章id*/
public function getCommentsJson($id) {
$model = M('comments');
$array = $model->where('archive=' . $id)->order('id asc')->select();
foreach ($array as $key => $value) {
$value["children"] = 'children';
$array[$key]['email'] = getGravatar($array[$key]['email']);
$array[$key]['children'] = array();
if ($value["reply"] != '0') {
//判断是否为父项
$array_children = $array[$key];
$array = $this->findParentNode($array, $array_children, $value["reply"]); //将有子项的回复代入findParentNode
}
}
//重新整理,讲数组根目录下,删除replyID的元素
$rtnArray = array();
$l = sizeof($array);
for ($i = 0; $i < $l; $i++) {
if ($array[$i]['reply'] == '0') {
array_push($rtnArray, $array[$i]);
}
}
print_r(json_encode($rtnArray));
}
/*****************嵌套回复测试片段*****************************/在前台模板中通过ajax请求ThinkPHP函数地址,并对json进行遍历根据层级输出。
comment.js
/*每条comment回复模板*/ var liTemplate = "
{#commentTxt#}
具体实现效果请看本文回复。
有19条评论