问答项目---栏目增删改方法示例
具体方法:
// 递归重新排序无限极子分类数组 function recursive($array,$pid=0,$level=0){ $arr = array(); foreach ($array as $v) { if($v['pid'] == $pid){ $v['level'] = $level; $v['html'] = str_repeat('--',$level); $arr[] = $v; $arr = array_merge($arr,recursive($array,$v['id'],$level+1)); } } return $arr; } //递归获取所有的子分类的ID function get_all_child($array,$id){ $arr = array(); foreach($array as $v){ if($v['pid'] == $id){ $arr[] = $v['id']; $arr = array_merge($arr,get_all_child($array,$v['id'])); }; }; return $arr; }
增删改方法示例:
<?php namespace Admin\Controller; use Think\Controller; class CategoryController extends Controller { public function index(){ $cateTopList = M('category')->select(); $cateTopList = recursive($cateTopList); $this->assign('cateTopList',$cateTopList); $this->display(); } public function addTop(){ $this->display(); } public function addCate(){ $data = I('post.'); if(M('category')->add($data)){ $this->success('添加成功', 'index'); }else{ $this->error('添加失败'); }; } // 添加子分类 public function addChild(){ $pid = I('get.pid'); $where = array('id' => $pid); $pCateName = M('category')->where($where)->getField('name'); $this->assign('pid',$pid); $this->assign('pCateName',$pCateName); $this->display(); } //修改分类 public function edit(){ $pid = I('get.pid'); $where = array('id' => $pid); $pCateName = M('category')->where($where)->getField('name'); $this->assign('pid',$pid); $this->assign('pCateName',$pCateName); $this->display(); } public function editCate(){ $post = I('post.'); $date = array( 'id' => $post['pid'], 'name' => $post['name'] ); if(M('category')->save($date)){ $this->success('修改成功','Index'); }else{ $this->error('修改失败'); }; } //删除分类 public function delCate(){ $get = I('get.pid'); $cateId = M('category')->field(array('id','pid'))->select(); $delId = get_all_child($cateId,$get); $delId[] = $get; $where = array( 'id' => array('IN',$delId) ); if(!M('category')->where($where)->delete()){ $this->error('删除失败'); }; $this->success('删除成功',U('index')); } }