|
中级会员
 
- 积分
- 398
- 威望
- 41
- CI版本
- 1.6.1
|
楼主
大 中
小 发表于 2008-4-13 10:02 只看该作者
根据parent_id递归的无限分类和下拉菜单。
先说下,这个对小树来讲还是很快的,大树没有测试,呵呵,递归对大树没什么优势。
数据库设计
id, title, parent_id, last
[int,char(255),int,bool]
MODEL:
先来个正常全部列表哦: 复制内容到剪贴板PHP 代码: function get_list() { $query = $this->db->get('catalog'); return $query->result_array(); } 在看一个根据parent_id自动生成的多维数组: 复制内容到剪贴板PHP 代码: function get_tree ($parent_id = null){$this-> db-> where('parent_id', $parent_id); $this-> db-> select('id,parent_id,last,title_english'); $query = $this-> db-> get('catalog'); $list['son'] = $query-> result_array(); foreach ($list['son'] as & $row) {if(array_key_exists('last', $row)){if(! $row['last']){$temp = $this-> get_tree($row['id']); //这里用了个递归$row['son'] = $temp['son']; }} }return $list; } 下一个是生成视图的下拉列表或者多级的菜单: 复制内容到剪贴板PHP 代码: function read_tree ($tree, $display = array( 'str_out'=>array ('open'=> "<ul>n", 'close'=> "</ul>n"), 'str_in'=> array('open'=> "<li>", 'close'=> "</li>n"), 'blank'=>array ('many'=> 0, 'what'=> ' ', 'increase'=> 0), 'attr'=>array ('value'=> 'id'), 'with_last' => true) ) { $str = ""; $str .= $display['str_out']['open']; foreach ($tree['son'] as $t) { if(array_key_exists('last', $t)) { $show = true; if($t['last']){if(! $display['with_last']){$show = false; }} if($show){ $str .= $display['str_in']['open']; if($display['attr'] != array()) { $str = substr($str, 0, strlen($str)-1); foreach ($display['attr'] as $k=> $v) { $str .= ' '. $k. '="'. $t[$v]. '"'; } $str .= '>'; } for($i= 0; $i< $display['blank']['many']; $i++ ) { $str .= $display['blank']['what']; } $str .= $t['title_english']. $display['str_in']['close']; } } if(array_key_exists('son', $t)) { // print_r($display); $str .= $this-> read_tree( $t, array('str_out'=> $display['str_out'], 'str_in'=> $display['str_in'], 'blank'=>array ( 'many'=> ($display['blank']['many']+ $display['blank']['increase']), 'what'=> $display['blank']['what'], 'increase'=> $display['blank']['increase'] ), 'attr' => $display['attr'], 'with_last'=> $display['with_last'], ) ); } } $str .= $display['str_out']['close']; return $str; } 控制器里调用: 复制内容到剪贴板PHP 代码: $tree = $this-> catalog_model-> get_tree(); echo '<select>'; echo $this-> catalog_model-> read_tree($tree, array('str_out'=>array ('open'=> '', 'close'=> ''), 'str_in'=>array ('open'=> '<option>', 'close'=> '</option>'), 'blank'=>array ('increase'=> 1, 'what'=> ' ', 'many'=> 0), 'attr'=>array ('value'=> 'id'), 'with_last'=>false )); echo '</select>'; 大家把echo的东西换成变量传递到视图里就可以啦。
参数设置的有点多,但是还是很好用D。
嘿嘿。数据结构学的不好,搞了半个下午。
希望能帮助更多的人。
CIAO,CI...
|