<?php
class MenuBuilder
{
var $conn;
var $items;
var $menu;
var $html;
function MenuBuilder()
{
$this->conn = mysqli_connect( 'localhost', 'user', 'pass', 'example' );
}
function fetch_assoc_all( $sql )
{
$result = mysqli_query( $this->conn, $sql );
if ( !$result )
return false;
$assoc_all = array();
while( $fetch = $result->fetch_assoc() )
$assoc_all[] = $fetch;
mysqli_free_result( $result );
return $assoc_all;
}
function get_menu_items()
{
$sql = 'SELECT id, parent_id, title, link, position FROM menu_item ORDER BY parent_id, position;';
return $this->fetch_assoc_all( $sql );
}
function build_menu_array()
{
$this->items = $this->get_menu_items();
if ( empty( $this->items ) )
return '';
foreach ( $this->items as $item )
$children[$item['parent_id']][] = $item;
$root = array();
$root['html_before'] = '<ul id="0">';
$root['html_after'] = '</ul>';
$parent = 0;
$tree = array();
$current_tree = &$tree;
$tree_stack = $parent_stack = array();
if ( empty( $children[$parent] ) )
return '';
while ( ( $option = each( $children[$parent] ) ) || ( $parent > 0 ) )
{
if ( $option === false )
{
unset( $current_tree );
$current_tree = &$tree_stack[count($tree_stack)-1];
array_pop( $tree_stack );
$parent = array_pop( $parent_stack );
}
elseif ( empty( $children[$option['value']['id']] ) )
{
$data = array();
$data['html'] = str_repeat( "\t", count( $tree_stack ) + 1 ) . '<li>' . $option['value']['title'] . '</li>';
$current_tree[] = $data;
}
else
{
$data = array();
$data['html_before'] = str_repeat( "\t", count( $tree_stack ) + 1 );
$data['html_before'] .= '<li>' . $option['value']['title'] . '</li>';
$data['html_before'] .= "\r\n" . str_repeat( "\t", count( $tree_stack ) + 1 );
$data['html_before'] .= '<ul id="' . $option['value']['id'] . '">';
$data['html_after'] .= str_repeat( "\t", count( $tree_stack ) + 1 ) . '</ul>';
$data_children = array();
$data['children'] = &$data_children;
$current_tree[] = $data;
$tree_stack[] = &$current_tree;
array_push( $parent_stack, $option['value']['parent_id'] );
unset( $current_tree );
$current_tree = &$data_children;
unset( $data_children );
$parent = $option['value']['id'];
}
}
$root['children'] = $tree;
return array( $root );
}
function build_item_html( $item )
{
foreach ( $item as $element )
if ( isset( $element['html'] ) )
$this->html[] = $element['html'];
else
{
$this->html[] = $element['html_before'];
$this->build_item_html( $element['children'] );
$this->html[] = $element['html_after'];
}
}
function get_menu_html( $item )
{
$this->html = array();
$this->menu = $this->build_menu_array();
$this->build_item_html( $this->menu );
return implode( "\r\n", $this->html );
}
}
$menu = new MenuBuilder();
echo '<pre>' . htmlentities( $menu->get_menu_html() ) . '</pŕe>';
?>