| 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 | @$html.='<li><b>'.$name.'</b> <small>('.$subtree[$index_id].' => '.$subtree[$index_path].')</small>'.render_tree($subtree).'</li>'; |
| 29 | } |
| 30 | $html.='</menu>'; |
| 31 | return $html; |
| 32 | } |
| 33 | echo render_tree($tree); |
| 34 | //print_r($tree); |