当前位置: 首页 > 面试题库 >

PHP递归目录路径

牛凌
2023-03-14
问题内容

我有此功能返回full directory tree

function getDirectory( $path = '.', $level = 0 ){

$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.

$dh = @opendir( $path );
// Open the directory to the handle $dh

while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

    if( !in_array( $file, $ignore ) ){
    // Check that this file is not to be ignored

        $spaces = str_repeat( ' ', ( $level * 4 ) );
        // Just to add spacing to the list, to better
        // show the directory tree.

        if( is_dir( "$path/$file" ) ){
        // Its a directory, so we need to keep reading down...

            echo "<strong>$spaces $file</strong><br />";
            getDirectory( "$path/$file", ($level+1) );
            // Re-call this same function but on a new directory.
            // this is what makes function recursive.

        } else {

            echo "$spaces $file<br />";
            // Just print out the filename

        }

    }

}

closedir( $dh );
// Close the directory handle

}

但是我想做的是搜索文件/文件夹并返回它的路径,我该怎么做?你有这样的功能,或者可以给我一些技巧吗?


问题答案:

尝试结合使用RecursiveIteratorIterator和RecursiveDirectoryIterator

$path = realpath('/path/you/want/to/search/in');

$objects = new RecursiveIteratorIterator(
               new RecursiveDirectoryIterator($path), 
               RecursiveIteratorIterator::SELF_FIRST);

foreach($objects as $name => $object){
    if($object->getFilename() === 'work.txt') {
        echo $object->getPathname();
    }
}


 类似资料:
  • 我想以前也有人问过类似的问题,但我不知道我想做的事情在逻辑上是否可行。 我目前在我们的内部网上使用DDSmoothMenu列出我们所有员工都可以访问的文档。 菜单结构类似于: 菜单的基本结构如下: 我认为它必须涉及某种多维数组和递归目录迭代器,但我希望遍历每个文件夹并创建如上所述的HTML布局。 我认为可以做开始标记,但不确定在目录全部列出后如何做结束标记。

  • 问题内容: 目录类似于: 我正在使用与PHPMyAdmin使用的相同的PHPZip类。我不确定如何压缩目录而不是仅压缩文件。这是我到目前为止的内容: 但是当我尝试解压缩相应的已下载的zip文件时,出现“不允许操作” 仅当我尝试在Mac上解压缩时,才出现此错误,当我通过命令行解压缩时,文件解压缩就可以了。我是否需要在下载时发送特定的内容类型,当前为“application / zip” 问题答案:

  • 本文向大家介绍PHP实现递归目录的5种方法,包括了PHP实现递归目录的5种方法的使用技巧和注意事项,需要的朋友参考一下 项目开发中免不了要在服务器上创建文件夹,比如上传图片时的目录,模板解析时的目录等。这不当前手下的项目就用到了这个,于是总结了几个循环创建目录的方法。 方法一:使用glob循环 方法二:使用dir && read循环 方法三:使用opendir && readdir循环  方法四:

  • 问题内容: 用Java查找具有特定名称的目录的最佳方法是什么?我要查找的目录可以位于当前目录或其子目录之一中。 问题答案: 您的解决方案将包括 API参考

  • 本文向大家介绍php递归删除目录与文件的方法,包括了php递归删除目录与文件的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了php递归删除目录与文件的方法。分享给大家供大家参考。具体实现方法如下: 希望本文所述对大家的PHP程序设计有所帮助。

  • 问题内容: 我试图将硬盘上的某些文件夹放入阵列中。 例如,度假图片。假设我们具有以下结构: 套装1 第一组的项目1 第一组的项目2 第1套​​的项目〜 套装2 组2的子集1 组2的子集1的项目1 组2的子集1的项目… 第2组的子集2 随机文件,而不是目录。 套装3 … 我想要像这样的东西作为数组。 意思是我有1个大数组,在那个数组中有更多数组。每个集合和子集都有自己的数组。 我正在尝试使其看起来像