First of all, you need to create a table like this:
CREATE TABLE IF NOT EXISTS `menus` (
`cid` int(10) NOT NULL,
`name` varchar(20) NOT NULL,
`parent_cat` int(10) NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `menus` (`cid`, `name`, `parent_cat`) VALUES
(1, 'numbers', 0),
(2, 'vowels', 0),
(3, 'one', 7),
(4, 'two', 7),
(5, 'a', 2),
(6, 'e', 2),
(7, 'ones', 1),
(8, 'tens', 1),
(9, 'ten', 8),
(10, 'twenty', 8);
Download this plug-in
and here is my php code for creating expand and collapse menu:
<?php
$viewsql = "SELECT * FROM menus";
$viewsqlres=mysql_query($viewsql);
while ( $viewsqlrow = mysql_fetch_array($viewsqlres)) {
$viewarray[$viewsqlrow['cid']] = array('cid'=>$viewsqlrow['cid'],'name' => $viewsqlrow['name'],'parent_cat' => $viewsqlrow['parent_cat']);
}
function view_generate_menu($parent_cat_view) //recursive function that prints category as a nested html unorderd list
{
$has_childs_view = false;
////this prevents printing 'ul' if we don't have subcategory for this category
global $viewarray;
////use global array variable instead of a local variable to lower stack memory requierment
foreach($viewarray as $key => $value_view) {
if ($value_view['parent_cat'] == $parent_cat_view) {
//if this is the first child print '<ul>'
if ($has_childs_view === false) {
//don't print '<ul>' multiple times
$has_childs_view = true;
?>
<ul id="tree">
<?php } ?>
<li><?php echo $value_view['name']; ?>
<?php
view_generate_menu($key);
////call function again to generate nested list for subcategory belonging to this category
echo '</li>';
}
}
if ($has_childs_view === true) echo '</ul>';
}
view_generate_menu(0);
?>
some styling:
<style>
#tree li {
list-style: none outside none;}
</style>
'; foreach($firstlevel as $key => $value) echo '- '.$value.'
';
echo '
'; – siva Nov 13 '14 at 04:59