Home > Article > Backend Development > PHP unlimited classification practice - comment and reply function_PHP tutorial
You can post first-level comments directly in the header, and the latest comments are displayed at the top, as shown in the following rendering
You can reply to posted comments, and the replies are displayed below the superior comments, forming a hierarchical relationship, as shown in the following rendering
Page operation details: When the reply button of a comment is clicked, the reply text input box is displayed, and the reply text input boxes of other comments disappear. When the reply button is clicked again, the text box disappears
Turn off the reply function at the last level of comment (the setting here is the third level)
Instantly display the total number of comments
(1). Recursively obtain the comment list
<code class="hljs" php="">/** *递归获取评论列表 */ protected function getCommlist($parent_id = 0,&$result = array()){ $arr = M('comment')->where(parent_id = '.$parent_id.')->order(create_time desc)->select(); if(empty($arr)){ return array(); } foreach ($arr as $cm) { $thisArr=&$result[]; $cm[children] = $this->getCommlist($cm[id],$thisArr); $thisArr = $cm; } return $result; }</code>
(2). Show the action of the comment page
<code class="hljs" lasso="">public function index(){ $num = M('comment')->count(); //获取评论总数 $this->assign('num',$num); $data=array(); $data=$this->getCommlist();//获取评论列表 $this->assign(commlist,$data); $this->display('index'); }</code>
(3). Comment page ajax access action to add comments
<code class="hljs" php="">/** *添加评论 */ public function addComment(){ $data=array(); if((isset($_POST[comment]))&&(!empty($_POST[comment]))){ $cm = json_decode($_POST[comment],true);//通过第二个参数true,将json字符串转化为键值对数组 $cm['create_time']=date('Y-m-d H:i:s',time()); $newcm = M('comment'); $id = $newcm->add($cm); $cm[id] = $id; $data = $cm; $num = M('comment')->count();//统计评论总数 $data['num']= $num; }else{ $data[error] = 0; } echo json_encode($data); }</code>
(1). Display the overall structural design of the page
Actual effect:
Page html code:
<code class="hljs" xml=""> </code>