dty3416 2016-01-31 12:06
浏览 67
已采纳

PHP计算scandir循环中的子目录级别

I got the following code that scans directory and outputs files and sub-folders in the following format:

file1.php
folder1
   file2.php
   folder2
       file3.php
file4.php

For my hyperlinks I need to refer to links with the number of levels. So for example: file1.php, folder1 and file4.php are all level number 1. file2.php, an folder2 is level 2, and file3.php is level 3.

Any advice on how I can use a loop counter to achieve this?

$directory = $_SERVER["DOCUMENT_ROOT"]."/files/";

function folderFleList($dir, $menu_class){
    $ffs = scandir($dir);
    echo "<ul class=\"".$menu_class."\">
";
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '<li class="menu-item"><a href="#" class="menu-link-level-1">'.$ff;
            if(is_dir($dir.'/'.$ff)) folderFleList($dir.'/'.$ff, "menu-sublist");
            echo '</a></li>';
        }
    }
    echo "</ul>
";
}

folderFleList($directory, "menu-list");
  • 写回答

1条回答 默认 最新

  • douao1579 2016-01-31 12:11
    关注

    Just add an extra parameter to your function:

    function folderFleList($dir, $menu_class, $level = 1){
        $ffs = scandir($dir);
        echo "<ul class=\"".$menu_class."\">
    ";
        foreach($ffs as $ff){
            if($ff != '.' && $ff != '..'){
                echo '<li class="menu-item">
                         <a href="#" class="menu-link-level-' . $level . '">'.$ff;
                if(is_dir($dir.'/'.$ff))
                    folderFleList($dir.'/'.$ff, "menu-sublist", $level+1);
                echo '</a></li>';
            }
        }
        echo "</ul>
    ";
    }
    
    folderFleList($directory, "menu-list");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部