<?php
* 纯属测试
* @author Mckee
* @link http://www.phpddt.com
class Category extends CI_Controller {
public function __construct()
parent::__construct();
$this->load->database();
public function view()
$lists = $this->db->order_by('lft', 'asc')->get('category')->result_array();
$parent = array();
$arr_list = array();
foreach($lists as $item){
if(count($parent)){
while (count($parent) -1 > 0 && $parent[count($parent) -1]['rgt'] < $item['rgt']){
array_pop($parent);
$item['depath'] = count($parent);
$parent[] = $item;
$arr_list[]= $item;
foreach($arr_list as $a)
echo str_repeat('--', $a['depath']) . $a['title'] . '<br />';
* 插入操作很简单找到其父节点,之后把左值和右值大于父节点左值的节点的左右值加上2,之后再插入本节点,左右值分别为父节点左值加一和加二
public function add()
$parent_id = 10;
$parent_category = $this->db->where('id', $parent_id)->get('category')->row_array();
$this->db->set('lft', 'lft + 2', FALSE)->where(array('lft >' => $parent_category['lft']))->update('category');
$this->db->set('rgt', 'rgt + 2', FALSE)->where(array('rgt >' => $parent_category['lft']))->update('category');
$this->db->insert('category', array(
'title' => '新的分类的子分类',
'lft' => $parent_category['lft'] + 1,
'rgt' => $parent_category['lft'] + 2,
'order' => 0,
'create_time' => time()
));
echo 'add success';
* #1.得到删除的节点,将右值减去左值然后加1,得到值$width = $rgt - $lft + 1;
* #2.删除左右值之间的所有节点
* #3.修改条件为大于本节点右值的所有节点,操作为把他们的左右值都减去$width
public function delete()
$id = 3;
$category = $this->db->where('id', $id)->get('category')->row_array();
$width = $category['rgt'] - $category['lft'] + 1;
$this->db->delete('category', array('id' => $id));
$this->db->delete('category', array('lft >' => $category['lft'], 'lft <' => $category['rgt']));
$this->db->set('lft', "lft - {$width}", FALSE)->where(array('lft >' => $category['rgt']))->update('category');
$this->db->set('rgt', "rgt - {$width}", FALSE)->where(array('rgt >' => $category['rgt']))->update('category');
echo 'delete success';
public function edit()
$id = 2;
$this->db->update('category', array(
'title' => '编辑后的分类'
), array(
'id' => $id
));
echo 'edit success';