Mikey1980
Mikey1980

Reputation: 1001

Dynamic Menu System

I am working on a dynamic menu system as the site I'm build has a strict naming convention.

For example, if I have a script are named AboutUs.php, then 'About Us' will be a Parent Menu Item. However if I have a script named Product.Product1.php then 'Product' is the Parent Item with 'Product1' as the Sub Menu Item.

The idea is to loop through grabbing all the scripts in my frontend folder and build an array so the ul/li elements can be echoed using a nested foreach

I just can't seem to get the Array and the $submenu) just right.. Thanks!

if ($handle = opendir('frontend/')) {
while(false !== ($sFile = readdir($handle))) {
    if (strrpos($sFile, ".php") === strlen($sFile)-strlen(".php")) {
        $pos1 = strrpos($sFile, ".");
        $menu = substr($sFile, 0, $pos1);
        $pos2 = strrpos($sFile, ".php");
        if ($pos1 == $pos2) { // "." and ".php" where in the pos, skip submenu
            $links[$menu] = 'fontend/'.$sFile;
        } else {
            $submenu = substr($sFile, $pos1, $pos2);
            $links[$menu][$submenu] = 'fontend/'.$sFile;
        }
    }
}

}

Upvotes: 0

Views: 224

Answers (2)

Ryan Kinal
Ryan Kinal

Reputation: 17732

It seems to me that you might be better off exploding on '.' instead of using strpos and regex.

while(false !== ($sFile = readdir($handle))) {
    if (strrpos($sFile, ".php") === strlen($sFile)-strlen(".php")) {
        $parts = explode('.', $sFile);
        if (count($parts) == 2)
        {
            $urls[$parts[0]] = 'frontend/'.$sFile;
        }
        else if (count($parts) == 3)
        {
            $urls[$parts[0]][$parts[1]] = 'frontend/'.$sFile;
        }
    }
}

Upvotes: 2

gablin
gablin

Reputation: 4798


if ($handle = opendir('frontend/')) {
while(false !== ($sFile = readdir($handle))) {
    if (strrpos($sFile, ".php") === strlen($sFile)-strlen(".php")) {
        $posExt = strrpos($sFile, "." );
        $menu = substr($sFile, 0, $pos1);
        $posSub = strrpos($menu, ".");
        if ($posSub === false) { // "." and ".php" where in the pos, skip submenu
            $urls[$menu] = 'fontend/'.$sFile;
        } else {
            $submenu = substr($menu, $posSub, ($posExt-$posSub));
            $urls[$menu][$submenu] = 'fontend/'.$sFile;
        }
    }
}

Haven't tested it, though, but it should work. ^^

EDIT: Fixed but in getting the $submenu. It's not unlikely to be a "off-by-1" error somewhere as well.

Upvotes: 1

Related Questions