Tuesday, August 15, 2017

Creating dynamic menu in php



$links = array();
    $links[0]['url'] = "/index2.php";
    $links[0]['text'] = "Home";
    $links[0]['selected'] = "";
    $links[1]['url'] = "/problem-videos/problem-videos.php";
    $links[1]['text'] = "Study";
    $links[1]['selected'] = "";
    $links[2]['url'] = "#";
    $links[2]['text'] = "Test";
    $links[2]['selected'] = "";
        $links[2]['sublinks'] = array();
        $links[2]['sublinks'][0]['url'] = "/tests/test-criteria.php";
        $links[2]['sublinks'][0]['text'] = "Take a Test";
        $links[2]['sublinks'][0]['selected'] = "";
        $links[2]['sublinks'][1]['url'] = "/tests/testHistory.php";
        $links[2]['sublinks'][1]['text'] = "Test History";
        $links[2]['sublinks'][1]['selected'] = "";
      $links[3]['url'] = "/analyze/";
    $links[3]['text'] = "Analyze";
    $links[3]['selected'] = "";
      $links[4]['url'] = "/myTutor/recommendation.php";
    $links[4]['text'] = "Recommendations";
    $links[4]['selected'] = "";

now print this array using foreach loop

<div id="menubar">
    <ul class="menu">
<?php
    foreach($links as $link) {
        if (strpos($_SERVER["REQUEST_URI"],$link['url'])!==false) $link['selected']="selected";
        echo '<li><a href ="'.$link['url'].'" class="'.$link['selected'].'">'.$link['text'].'</a>';
        if (isset($link['sublinks'])) {
            echo "<ul>";
            foreach($link['sublinks'] as $sublink) {
            if (strpos($_SERVER["REQUEST_URI"],$sublink['url'])!==false) $sublink['selected']="selected";
                        echo '<li><a href="'.$sublink['url'].'" class="'.$sublink['selected'].'">'.$sublink['text'].'</a></li>';
            }
            echo "</ul>";
        }
        echo "</li>";
    }
?>   
    </ul>
</div>

No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...