Tree Structure Menu with php Using Recursive


CREATE TABLE IF NOT EXISTS `menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_parent` int(11) NOT NULL DEFAULT '0',
`link` varchar(255) NOT NULL,
`order` int(11) NOT NULL DEFAULT '0',
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_polish_ci NOT NULL DEFAULT '',
`level` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;

INSERT INTO `menu` (`id`, `id_parent`, `link`, `order`, `title`, `level`) VALUES
(12, 0, '', 0, 'Office Furniture', 0),
(13, 12, '', 0, 'Chairs', 0),
(14, 12, '', 0, 'Work Tables', 0),
(15, 12, '', 0, 'Workstations', 0),
(16, 12, '', 0, 'Storage', 0),
(17, 12, '', 0, 'Conference Tables', 0),
(18, 13, '', 0, 'with spagh', 0),
(19, 13, '', 0, 'without spagh', 0),
(20, 18, '#', 0, 'Triangle', 0),
(21, 18, '#', 0, 'Sqare', 0),
(22, 19, '#', 0, 'Simple', 0),
(23, 19, '#', 0, 'Complex', 0);

PHP Code for that example

"SET NAMES utf8"));

function createsubmenu( $item )
{
global $db;
// prepare a query to get subitems of the current $item (those with parent = $item)
$subsel = $db->prepare('SELECT id, link, title, level FROM menu WHERE id_parent = :parent ORDER BY `order`');
// run the query
$subsel->execute(array('parent' => $item));
$text = '';
// fetch one row at a time, when no more rows are available $i
// will be false and while ends
while( ($i = $subsel->fetch(PDO::FETCH_OBJ)) !== false ) {
// generate code for the current $item
// will recursively call createsubmenu to add possibly existing subitems
$text .= '

  • level - 1) . '">'
    .'link) . '">' . htmlspecialchars($i->title) . ''
    . createsubmenu($i->id) . '
  • ';
    }
    // there were no items for the current call
    if( $text == '' )
    return '';
    // items were found, wrap them in an unordered list
    return '

      ' . $text . '

    ';
    }

    echo createsubmenu(0);
    ?>

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s