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 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题