简体   繁体   中英

PHP recursive directory menu

I think similar questions have been asked before, but I can't quite wrap my head around whether what I want to do is logicaly possible.

I currently use DDSmoothMenu on our intranet to list documents that we have for all staff to access.

Menu structure would be something like:

Documents -> Finance -> Forms -> File 1
                              -> File 2
                              -> File 3
                     -> Informational -> File 1
                                      -> File 2
          -> Insurance -> File 1
                       -> File 2

The basic structure of the menu is below:

<ul>
  <li><a href='#'>Sub Menu Name</a>
    <ul>
      <li><a href='#'>Menu Item</a></li>
      <li><a href='#'>Menu Item</a></li>
      <li><a href='#'>Menu Item</a></li>
      <li><a href='#'>Menu Item</a></li>
    </ul>
  </li>
</ul>

I think it would have to involve some kind of multidimensional array and a recursive directory iterator, but I would like to go through each folder and create the HTML layout as above.

I think it may be possible to do the opening tags, but not sure how to then do the closing tags once that directory is all listed.

The easier way is use trees. I recommend Nested model You can check current and perv lvl of item.

A recursive solution could look something like:

function createMenuHTML($dir){
    $html = "";
    if(is_dir($dir)){
        //Directory - add sub menu
        $html .= "<li><a href='#'>Sub Menu Name</a><ul>";
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
                $html .= createMenuHTML($dir.$file);
            }
            closedir($dh);
        }
        $html .= "</ul>"
    }else{
        //File so  just add list item
        $html .= "<li><a href='#'>".basename($dir)."</a></li>"
    }
    return $html;
}

This is entirely untested but should hopefully help.

Ok, so here is what I ended up with thanks to Jim's example code:

    function createMenu($dir) {
    if(is_dir($dir)) {
        echo "<li><a href='#'>".basename($dir)."</a><ul>";
        foreach(glob("$dir/*") as $path) {
            createMenuHTML($path);
        }
        echo "</ul></li>";
    }
    else {
        $extension = pathinfo($dir);
        $extension = $extension['extension'];
        echo "<li><a href='$dir'>".basename($dir, ".".$extension)."</a></li>";
    }
}

createMenu("/public/Documents");

Works like an absolute charm for my DDSMoothMenu, and I can be as general or as granular as I want when using the function to create the menu.

I will mark this as the answer, but Jim gave me the best starting point possible code wise!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM