views:

29

answers:

2

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;
        }
    }
}

}

+1  A: 

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.

gablin
+2  A: 

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;
        }
    }
}
Ryan Kinal
Ah yes, that would produce a much more elegant solution.
gablin
that is sexy.. works like a charm too--many thanks!
Mikey1980
Heh, no problem. Always glad to help!
Ryan Kinal