小型论坛的实现

代码实现

<?php
namespace Service\Controller;

use Think\Controller;

class BbsController extends Controller
{
    /**
     * 留言大厅
     */
    public function index()
    {
        $bbs = M('bbs')->where(array('pid'=>0))->order('id desc')->select();  //uid联合用户表


        foreach ($bbs as &$v)
        {
            $re = M('bbs')->where(array('pid'=>$v['id']))->order('id desc')->find();
            $v['reply'] = $re['content'];
        }

        $this->assign('bbs',$bbs);
        $this->display();
       // $this->websucess('100000','y',$bbs);
    }

    public function addpage()
    {
        $this->display();
    }

    /**
     * 添加留言
     */
    public function add()
    {

        $uid = $_POST['uid'];
        $id = $_POST['id'];
        $content = $_POST['content'];
        if ($id){
            $data = array(
//            'uid'=>$this->uid,
                'uid'=>$uid,
                'content'=>$content,
                'status'=>0,
                'type'=>1,
                'pid'=>$id,
                'add_time'=>time()
            );
        }else{
            $data = array(
//            'uid'=>$this->uid,
                'uid'=>$uid,
                'content'=>$content,
                'status'=>0,
                'type'=>1,
                'pid'=>0,
                'add_time'=>time()
            );
        }

        $re = M('bbs')->add($data);
        if ($re)
        {
            $this->success('添加成功','/service/bbs/index');
        }else{
            $this->success('添加失败','/service/bbs/add_page');
        }

    }

    /**
     * 留言详请
     */
    public function detail()
    {
//        $id = $_POST['id'];
        $id =1;
        $re = self::recursionbbs($id);

        foreach ($re as $v)
        {
            echo str_repeat('--',$v['level']).$v['uid'].$v['content']."<br>";
        }

//        $this->websucess('100000','y',$re);
    }

    /**
     * 递归出所有的留言信息
     * @param $id 留言id
     */
    public function recursionbbs($id,$level=0)
    {
        static $arr = array();
        $results =  M('bbs')->where(array('pid'=>$id))->select();

        foreach ($results as &$result)
        {

            if ($result)
            {
                $result['level']=$level;
                $arr[] = $result;
                self::recursionbbs($result['id'],$level+1);
            }else{
                return ;
            }
        }

        return $arr;
    }

}

主要就是递归

数据表设计

CREATE TABLE `yixiang_bbs` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
 `uid` int(11) NOT NULL COMMENT '用户id',
 `content` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '留言内容',
 `pid` int(11) NOT NULL COMMENT '父级id',
 `status` int(11) NOT NULL COMMENT '状态',
 `type` int(11) NOT NULL COMMENT '类型',
 `add_time` int(11) NOT NULL COMMENT '添加时间',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

猜你喜欢

转载自blog.csdn.net/kevlin_V/article/details/103620006