Tree menu expand and collapse using PHP

7.7k views Asked by At

I have following array:

$firstlevel=array(“numbers”,”vowels”,”animals”,”birds”);    
$numbers=array(“one”,”two”,”three”);    
$vowels= array (“a”,”e”,”i”,,”o”,”u”);    
$animals=array(“lion”,”tiger”,”dog”,”wolf”,”horse”,”Zebra”);    
$birds=array(“parrot”,”sparrow”,”crow”);

I need tree menu like below:(ONLY BY USING PHP)

+ numbers
+ vowels
+ animals
+ birds

 Reset button

When clicking it expands like following:

+ Fruits
- Vegetables
  + Drumstick
  + Lady’s finger
+ Animals
+ Birds

The same format should be retain once we click on the other first level item its corresponding child nodes to be in expanded.

3

There are 3 answers

0
Ramesh Singh On

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>
0
Arun On
use jquery with php u will get i did same thing try this......
include this first

<div class="menu_list" id="secondpane"> <!--Code for menu starts here-->
        <p class="menu_head">Data Warehousing</p>
        <div class="menu_body">
        <a href="teradata.php">Teradata Online training</a>
         <a href="data-warehousing.php">Informatica Online training</a>
         <a href="#">Cognos Online training</a> 
        </div>
        <p class="menu_head">SAP</p>
        <div class="menu_body">
         <a href="#">SAP BO</a>
         <a href="sap-abap.php">SAP ABAP</a>
         <a href="#">SAP BI/BW</a>
         <a href="#">SAP FICO</a>
         <a href="#">SAP HR</a> 
        </div>
        <p class="menu_head">ORACLE</p>
        <div class="menu_body">
          <a href="#">ORACLE DBA</a>
         <a href="#">ORACLE 11g</a>
       </div>
       <p class="menu_head">SQL</p>
        <div class="menu_body">
          <a href="#">SQL DBA</a>
       </div>
        <p class="menu_head">JAVA</p>
        <div class="menu_body">
          <a href="core-java.php">Core JAVA</a>
         <a href="advanced-java.php">Advanced JAVA</a>
       </div>
        <p class="menu_head">SAS</p>
        <div class="menu_body">
          <a href="#">SAS BI</a>
         <a href="#">SAS CDM</a>
       </div>
        <p class="menu_head">Testing Tools</p>
        <div class="menu_body">
          <a href="#">Manual Testing+QTP Training</a>
         <a href="#">ETL Testing</a>
         <a href="#">SELENIUM Training</a>          
       </div>
       <p class="menu_head">Android Training</p>
       <div class="menu_body">
          <a href="android.php">Android Course</a>

       </div>
       <p class="menu_head">Sharepoint Training</p>
       <p class="menu_head">.NET Training</p>
        <div class="menu_body">

         <a href="#">ASP .NET Training</a>
         <a href="#">C# Training</a>            
       </div>
  </div>

add these styles

@charset "utf-8";
/* CSS Document */


body {
    margin: 10px auto;
    font: 105%/140% Verdana,Arial, Helvetica, sans-serif;
}
.menu_list {    
    width:250px;
}
.menu_head {
    padding: 5px 10px;
    cursor: pointer;
    position: relative;
    margin:1px;
    font-weight:bold;
    background:#83C7DA url(left.png) center right no-repeat;
    font-size:15px;
    color:black;
    border-radius:5px;
}
.menu_body {
    display:none;
}
.menu_body a{
    display:block;
    color:#C00;
    background-color:#EFEFEF;
    padding-left:10px;
    font-weight:bold;
    text-decoration:none;
}
.menu_body a:hover{
  color: #000000;
  text-decoration:underline;
  }

integrate jQuery.js library then only it will work.....
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
<!--//---------------------------------+
//  Developed by Roshan Bhattarai 
//  Visit http://roshanbh.com.np for this script and more.
//  This notice MUST stay intact for legal use
// --------------------------------->
$(document).ready(function()
{

    //slides the element with class "menu_body" when mouse is over the paragraph
    $("#secondpane p.menu_head").mouseover(function()
    {
         $(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideDown(500).siblings("div.menu_body").slideUp("slow");
         $(this).siblings().css({backgroundImage:"url(left.png)"});
    });
});
</script>
2
bhargav3vedi On

This is For pure css, js and html code. For php refer next section.

$(document).ready(function(){
       $('.child').hide(); 
});
$( "a" ).click(function() {
Show(this);
});

function Show(obj)
    {
      var ObjId = obj.id;
        var Obj = ObjId.split('-');
        var id = Obj[0];
        
        var symb = $('#'+id+'-symbol').html();
        
        if(symb.trim() == "+")
        {
            $('#'+id).show(1000);
            $('#'+id+'-symbol').html("- ");
        }
        else
        {
            $('#'+id).hide(1000);
            $('#'+id+'-symbol').html("+ ");
        }
        
    }
ul {
        list-style: none;
        margin-left:10px;
    }
ul>li{
  margin-left:15px;
  padding-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
    <a id='fruit-a' style='text-decoration:none; color:black;' href='#'>
    <span  id='fruit-symbol'>+ </span>
      Fruit
    </a>
    <ul class='child'  id='fruit'>
      <li>* numbers</li>
      <li>* vowels</li>
      <li>* animals</li>
      <li>* birds</li>
      
    </ul>
  </li>
</ul>

You can do it like this with php.

<html>
<head>
<style>
    ul {
        list-style: none;
    }

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('.child').hide();
    });

    function Show(id)
    {
        var symb = $('#'+id+'-symbol').html();

        if(symb.trim() == "+")
        {
            $('#'+id).show(1000);
            $('#'+id+'-symbol').html("- ");
        }
        else
        {
            $('#'+id).hide(1000);
            $('#'+id+'-symbol').html("+ ");
        }

    }

</script>
</head>
<body>

<?php

$firstlevel=array("numbers","vowels","animals","birds");    
$numbers=array("one","two","three");    
$vowels= array ("a","e","i","o","u");    
$animals=array("lion","tiger","dog","wolf","horse","Zebra");    
$birds=array("parrot","sparrow","crow");

$AllArray = ["firstlevel", "numbers", "vowels", "animals", "birds"];

echo "<ul>";

foreach($AllArray as $a)
{

    echo "<li><a onclick=\"Show('".$a."')\" style='text-decoration:none; color:black;' href='#'><span  id='".$a."-symbol'>+ </span>".$a."</a><ul class='child'  id='".$a."'>";

    foreach($$a as $id=>$val)
    {
        echo "<li>* ".$val."</li>";
    }

    echo "</ul></li>";
}

echo "</ul>";

?>
</body>
</html>

You can see result through this link https://www.tehplayground.com/5SHAWKeEcsm5O5Ww