tp取无限级分类

来源:互联网 发布:java 未来前景 编辑:程序博客网 时间:2024/06/04 17:53
  • controller
public function listAction(){    // 判断缓存是否存在    // 初始化缓存配置     S([    'type' => 'memcache',     'host' => '127.0.0.1',     'port' => '11211'    ]);    $cat_tree = S('cat_tree');    if (false === $cat_tree){        echo 'non-cache';        $m_cat = D('Cat');        $cat_tree = $m_cat->getTreeList();        S('cat_tree', $cat_tree);    }    $this->assign('list', $cat_tree, PHP_INT_MAX);    $this->display();}public function deleteAction($cat_id){    $m_cat = D('Cat');    if ($m_cat->delete($cat_id)){        S([        'type' => 'memcache',         'host' => '127.0.0.1',         'port' => '11211'        ]);        S('cat_tree', NULL);        $this->success('删除成功', U('Back/Cat/list'), 0);    } else {        $this->error('删除失败', U('Back/Cat/list'));    }}
  • model
class CatModel extends \Think\Model {    protected $tablename = 'category';    public function getTreeList(){        $list = $this->order('sort_order desc')->select();        return $this->_getTree($list, 0, 0);    }    protected function _getTree($rows, $p_id=0, $deep=0){        static $tree = [];        foreach($rows as $row){            if($row['parent_id'] == $p_id){             $row['deep'] = $deep;             $tree[] = $row;             $this->_getTree($rows, $row['cat_id'], 1+$deep);            }        }    }}
原创粉丝点击