Asked  8 Months ago    Answers:  5   Viewed   32 times

Well, to build my menu my menu I use a db similar structure like this

  2  Services                  0
  3  Photo Gallery             0
  4  Home                      0
  5  Feedback                  0
  6  FAQs                      0
  7  News & Events             0
  8  Testimonials              0
 81  FACN                      0
 83  Organisation Structure   81
 84  Constitution             81
 85  Council                  81
 86  IFAWPCA                  81
 87  Services                 81
 88  Publications             81

To assign another submenu for existing submenu I simply assign its parent's id as its value of parent field. parent 0 means top menu

now there is not problem while creating submenu inside another submenu

now this is way I fetch the submenu for the top menu

<ul class="topmenu">
    <? $list = $obj -> childmenu($parentid); 
        //this list contains the array of submenu under $parendid
        foreach($list as $menu) {
            extract($menu);
            echo '<li><a href="#">'.$name.'</a></li>';
        }
    ?>
</ul>

What I want to do is.

I want to check if a new menu has other child menu

and I want to keep on checking until it searches every child menu that is available

and I want to display its child menu inside its particular list item like this

<ul>       
       <li><a href="#">Home</a>
        <ul class="submenu">
           ........ <!-- Its sub menu -->
           </ul>
       </li>
</ul>

 Answers

92

You need to use recursive functions for this. Technically, there's a few ways to do it, but recursion is really the best option here.

Here's the basic gist of how it would work:

function drawMenu ($listOfItems) {
    echo "<ul>";
    foreach ($listOfItems as $item) {
        echo "<li>" . $item->name;
        if ($item->hasChildren()) {
            drawMenu($item->getChildren()); // here is the recursion
        }
        echo "</li>";
    }
    echo "</ul>";
}

The properties and methods of $item are just examples, and I'll leave it up to you to implement these however you need to, but I think it gets the message across.

Wednesday, March 31, 2021
 
IcedAnt
answered 8 Months ago
70

I have the same requirement like yours and workout with that take a look on my code which is almost same as yours,

Here is my Controller:

public function select_menu_priority() {
        $data['product'] = $this->menu_model->select_menu_priority();

        $data['li'] = $this->generate_li($data['product']);

        $this->load->view("set_menu_priority_table", $data);
    }

function generate_li($product,$parent = NULL){

        $li = "";

        $p1 = array_filter($product, function($a)use($parent){ return $a['parent_menu_id'] == $parent; });

        foreach ($p1 as $p){

            $inner_li = "";

            $p2 = array_filter($product,function($a)use($p){ return $a['parent_menu_id'] == $p['id']; });

            if($p2){
                $inner_li = $this->generate_li($product,$p['id']);
            }

            $li .= "<li class='dd-item' data-id='".$p['id']."'><div class='dd-handle'>".$p['title']."</div>".$inner_li."</li>";

        }

        $ol = "<ol class='dd-list'>".$li."</ol>";

        return $ol;
    }

View set_menu_priority_table.php:

<?php
if (isset($product)) {    
    $entity = $this->input->post("entity");
    $entity = $entity['id'];
    if (count($product) > 0) {
        ?>
        <div class="row-fluid" style="margin-bottom: 10px;">
            <button class="btn btn-success btn-sm" tabindex="4" id="save">
                <i class="fa fa-check"></i> Save
            </button>
            <p class="pull-right" style="margin-bottom: 10px;"><?php if ($entity == "product") { ?><a href="javascript:void(0)" id="show_category" class="text-success" style="margin-right:10px;font-weight: bold;text-decoration: underline">Go to Category Priority</a><?php } ?><span class="label label-info ">Drag Menu to set Priority.</span></p>            
            <div class="clear"></div>
        </div>
        <div class="dd" id="product_list">
            <input type="hidden" id="entity_type" name="entity" value="<?php echo $entity ?>" />    
            <?php echo $li; ?>
        </div>
    <?php } else { ?>        
        <p><span class="label label-warning">No <?php echo ($entity == "product") ? "product" : "category"; ?> found.</span><?php if ($entity == "product") { ?><a href="javascript:void(0)" id="show_category" class="text-success" style="margin-left:15px;font-weight: bold;text-decoration: underline">Go to Category Priority</a><?php } ?></p>            
        <?php
    }
} else {
    ?>
    <p class="label label-info">Please select Category to Set Priority within the Category.</p>
<?php } ?>

<script type="text/javascript">
$("#save").off("click").on("click", function() {
            var product_data = $("#product_list").nestable("serialize");
            var data = {product_data: product_data, entity: $("#entity_type").val()};
            if ($.bbq.getState("product_category") !== undefined) {
                data['product_category'] = $.bbq.getState("product_category");
            }
            ajax_call({
                url: '<?php echo site_url("admin/menu/update_menu_priority");?>',
                type: "post",
                dataType: "json",
                data: data,
                beforeSend: function() { },
                success: function(result) {
                    if (result['status'] == "success") {
                        alert("Priority Updated!");
                    } 
            });
        });
</script>

For Update That Priority Add function update_menu_priority in Controller:

public function update_menu_priority() {
            $data = $this->input->post("product_data");
            if (count($data)) {
                $update = $this->menu_model->update_priority_data($data);
                if ($update) {
                    $result['status'] = "success";
                } else {
                    $result['status'] = "error";
                }
            } else {
                $result['status'] = "error";
            }
            echo json_encode($result);

    }

And at last ad model function for that update_priority_data:

function update_priority_data($data, $parent = NULL) {
        $i = 1;
        foreach ($data as $d) {
            if (array_key_exists("children", $d)) {
                $this->update_priority_data($d['children'], $d['id']);
            }
            $update_array = array("priority" => $i, "parent_menu_id" => $parent);
            $update = $this->db->where("id", $d['id'])->update("menu", $update_array);
            $i++;
        }
        return $update;
    }

I hope this would be help full to you, thanks.

Saturday, May 29, 2021
 
altermativ
answered 5 Months ago
78

Menu Tree

a. Create the table "categorylist".

CREATE TABLE IF NOT EXISTS `categorylist` (
`id` int(5) NOT NULL auto_increment,
`cname` varchar(25) collate utf8_unicode_ci default NULL,
`pid` int(5) NOT NULL,
`url` text collate utf8_unicode_ci,
`status` int(1),
PRIMARY KEY (`id`),
KEY `pid` (`pid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=9 ;

b. Insert values in the "categorylist"

INSERT INTO `categorylist` (`id`, `cname`, `pid`, `url`, `status`) VALUES
(1, 'Entertainment', 0, '#',1),
(2, 'Movies', 1, 'http://example.com/movie.php',1),
(3, 'Drama', 1, 'http://example.com/drama.php',1),
(4, 'Sports', 0, '#',1),
(5, 'Football', 4, 'http://example.com/football.php',1),
(6, 'Cricket', 4, 'http://example.com/cricket.php',1),
(7, 'Politics', 0, '#',1),
(8, 'Politics news', 7, 'http://example.com/politics-news.php',1);

c. Style sheet

.nav ul li { background:#f1f1f1; list-style: none;}
ul.dropdown { position:relative; width:auto; font:12px Arial, Helvetica, sans-serif; }
ul.dropdown li { float:left; zoom:1; height:30px; padding:6px 2px 0 2px; }
ul.dropdown li li { border-right:1px solid #ccc; border-left:1px solid #ccc; margin-left:-30px;}
ul.dropdown a:hover { color:#000; } ul.dropdown a:active { color:#ffa500; }
ul.dropdown li a { display:block; padding:4px 8px; color:#000; text-decoration:none; font:bold 12px Arial, Helvetica, sans-serif; }
ul.dropdown li:last-child a { border-right:none;} /* Doesn't work in IE */
ul.dropdown li:hover { color:#000; background:#e7e7e7; position:relative; }
ul.dropdown li.hover a { color:#000; }
ul.dropdown ul { text-align:left; visibility: hidden; position: absolute; left:-10px; top:36px; }
ul.dropdown ul li { background:#f1f1f1; border-bottom:1px solid #ccc; float:none; width:120px; height:25px; }
ul.dropdown ul li a { border-right:none; width:100%; display:inline-block; color:#000; }
ul.dropdown ul ul { left:100%; top:0; }
ul.dropdown li:hover > ul { visibility:visible; }

d. Code for menu script

<?php

$con=mysql_connect("localhost", "root", "") or die('Server connexion not possible.');
mysql_select_db("newone",$con) or die('Database connexion not possible.');

$qry="SELECT * FROM categorylist" where status=1;
$result=mysql_query($qry,$con);


$arrayMenu = array();

while($row = mysql_fetch_assoc($result)){
$arrayMenu[$row['id']] = array("pid" => $row['pid'], "name" => $row['cname'], "url" => $row['url']);
}


//createTree($arrayCategories, 0);

function createTree($array, $curParent, $currLevel = 0, $prevLevel = -1) {

foreach ($array as $categoryId => $category) {

if ($curParent == $category['pid']) {

if($category['pid']==0) $class="dropdown"; else $class="sub_menu";
if ($currLevel > $prevLevel) echo " <ul class='$class'> ";


if ($currLevel == $prevLevel) echo " </li> ";

echo '<li id="'.$categoryId.'" >&lt;a href="'.$category['url'].'"&gt;'.$category['name'].'&lt;/a&gt;';

if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }

$currLevel++;

createTree ($array, $categoryId, $currLevel, $prevLevel);

$currLevel--;
}
</pre>
}

if ($currLevel == $prevLevel) echo " </li> </ul> ";

}
?>

<div class="nav">

<?php
if(mysql_num_rows($result)!=0)
{
php createTree($arrayMenu, 0);
}
?>
</div>
Saturday, May 29, 2021
 
muaaz
answered 5 Months ago
70

The PDO mssql driver is no more, use sqlsrv (under php windows) or dblib (under php linux)

http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx

http://www.php.net/manual/en/ref.pdo-dblib.php

Thursday, June 3, 2021
 
barden
answered 5 Months ago
39

yo need create the user "pma" in mysql or change this lines(user and password for mysql):

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma'; 
$cfg['Servers'][$i]['controlpass'] = '';

Linux: /etc/phpmyadmin/config.inc.php

Tuesday, July 13, 2021
 
ShadowZzz
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share