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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊