dongmu5106 2014-06-27 09:01
浏览 25
已采纳

PHP列表目录递归发布

I'm trying to list all PHP files in a specified directory and for it to recursively check all sub-directories until it finds no more, there could be numerous levels.

The function I have below works fine with the exception that it only recurses down one level.

I've spent hours trying to see where I'm going wrong, I'm calling the scanFiles() when it finds a new directory but this only seems to work one level down and stop, any help greatly appreciated.

Updated:

function scanFiles($pParentDirectory)
{
    $vFileArray = scandir($pParentDirectory);
    $vDirectories = array();

    foreach ($vFileArray as $vKey => $vValue)
    {
        if (!in_array($vValue, array('.', '..')) && (strpos($vValue, '.php') || is_dir($vValue)))
        {
            if (!is_dir($vValue))
                $vDirectories[] = $vValue;
            else
            {
                $vDirectory = $vValue;
                $vSubFiles = scanFiles($vDirectory);
                foreach ($vSubFiles as $vKey => $vValue)
                        $vDirectories[] = $vDirectory.DIRECTORY_SEPARATOR.$vValue;
            }
        }
    }

    return $vDirectories;
}
  • 写回答

3条回答 默认 最新

  • douluhaikao93943 2014-06-27 09:14
    关注

    You can do this easily like this:

    // helper function
    function getFiles(&$files, $dir) {
        $items = glob($dir . "/*");
        foreach ($items as $item) {
             if (is_dir($item)) {
                getFiles($files, $item);
            } else {
                if (end(explode('.', $item)) == 'php') {
                    $files[] = basename($item);
                }
            }
        }
    }
    
    // usage
    $files = array();
    getFiles($files, "myDir");
    
    // debug
    var_dump($files);
    

    myDir looks like this: has php files in all dirs

    enter image description here

    Output:

    enter image description here


    P.S. if you want the function to return the full path to the found .php files, remove the basename() from this line:

    $files[] = basename($item);
    

    This will then produce result like this:

    enter image description here

    hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?