CI 实现评论盖楼(递归)

目的:实现某个商家店铺下的评论可无限引用回复(盖楼效果)

一、数据简单设计

ID 主键

content 评论内容

pid 父ID

二、读取数据(model)

/**
* 获取某个商家店铺下的所有点评
*
* @param $store_id int
* 店铺ID
* @return $result 数组或空
*/
function get_comment_list($store_id) {
$result = array ();
$sql = “Select * From `carshop_store_comment` where store_id=’$store_id’ “;
$query = $this->db->query ( $sql );
if ($query->num_rows () > 0) {
$result = $query->result_array ();
} else {
$result = ”;
}
return $result;
}
/**
* 获取某条评论详细
*
* @param $id int
* 评论ID
* @return array
*/
function get_comment_detail($id) {
$result = array ();
$sql = “Select id,pid,content From `carshop_store_comment` where id=’$id’ “;
$query = $this->db->query ( $sql );
if ($query->num_rows () > 0) {
$result = $query->result_array ();
} else {
$result = ”;
}
return $result;
}

三、前台输出(controler)

/**
* 输出评论
* @author 火柴
* @param array $comments
*/
private function _showComments($comments){
if(!empty($comments)){
$html = ”;
foreach ($comments as $value){
if($value['pid']==0){
$html .= ‘

’.$value['content'].’
’;
continue;
}else{
$html .= ‘
’.$this->_showUpcomments($value['pid'],’  ’).’’.$value['content'].’
’;
continue;
}
}
return $html;
}else{
return ”;
}
}
/**
* 递归输出评论多级引用(盖楼)
* @param int $id
* @param varchar $tag
* @return string
*/
private function _showUpcomments($id,$tag){
$detail=$this->store_model->get_comment_detail($id);
foreach ($detail as $key=>$v){
if($v['pid']==0){
return ‘
’.$v['content'].’
’;
continue;
}else{
return ‘
’.$this->_showUpcomments($v['pid'],’  ’).’’.$tag.$v['content'].”
”;
continue;
}
}
}


输出:

$comments=$this->store_model->get_comment_list($store_id);
$result=$this->_showComments($comments);

print_r($result);

最终效果:

20121228093202


分享至
2013-04-23 发布 ┊ 5737 人浏览 ┊ 0 人评论 ┊ 来源:原创 ┊ 收藏
返回顶部