| 1 | <pre><?php |
| 2 | $result = $this->db->safe_query_fetch('SELECT * FROM category'); |
| 3 | |
| 4 | function addleaf(&$tree, $levels, $id, $category='') { |
| 5 | if(!count($levels)) { |
| 6 | $tree['__ID__'] = $id; |
| 7 | return; |
| 8 | } |
| 9 | $current = array_shift($levels); //echo("$current ".count($levels).""); |
| 10 | $category .= '/'.$current; |
| 11 | if(!isset($tree[$current])) $tree[$current] = array(); |
| 12 | $tree[$current]['__PATH__'] = $category; |
| 13 | //if(!count($levels)) $tree[$current]['__ID__'] = $id; //echo "($current $id)\n"; |
| 14 | addleaf($tree[$current], $levels, $id, $category); |
| 15 | } |
| 16 | |
| 17 | $tree = array(); |
| 18 | foreach($result as $row) { |
| 19 | $row_parts = preg_split('/\//', $row['category_name']); |
| 20 | //echo($row['category_name'].$row['category_id']."\n"); |
| 21 | addleaf($tree, $row_parts, $row['category_id']); |
| 22 | } |
| 23 | |
| 24 | function render_tree($tree, $index_path='__PATH__', $index_id='__ID__') { |
| 25 | if(!is_array($tree)) return ''; |
| 26 | $html='<menu>'; |
| 27 | foreach($tree as $name => $subtree) if($name != $index_path && $name != $index_id) { |
| 28 | $link = isset($subtree[$index_id]); |
| 29 | $hidden = $link && $subtree[$index_id] <= 0; |
| 30 | |
| 31 | $html.='<li>'; |
| 32 | if($link) $html.= '<a href="'.$_SERVER['SCRIPT_NAME'].'/model/?where[category_id]=='.$subtree[$index_id].'">'; |
| 33 | if($hidden) $html.='<font color="grey">'; |
| 34 | $html.="<b>$name</b>"; |
| 35 | if($hidden) $html.='</font>'; |
| 36 | if($link) $html.= '</a>'; |
| 37 | @$html.=' <small>('.$subtree[$index_id].' => '.$subtree[$index_path].')</small>'; |
| 38 | $html.=render_tree($subtree); |
| 39 | $html.='</li>'; |
| 40 | } |
| 41 | $html.='</menu>'; |
| 42 | return $html; |
| 43 | } |
| 44 | echo render_tree($tree); |
| 45 | //print_r($tree); |