2009-12-15 107 views
2

下面的函数将给定目录中的所有文件夹返回到多个级别。使用glob返回给定目录中的文件夹列表(不含路径)

我只需要一个级别的深度,只是目标目录中的文件夹,没有子文件夹。

另外该函数返回文件夹的完整路径,我只想要文件夹名称。我确定我错过了一些简单的东西。

如何修改函数以仅返回给定目录的文件夹名称? (不是每个文件夹的完整路径)

$ myArray = get_dirs('../ wp-content/themes/mytheme/images');

<?php 
    function get_dirs($path = '.'){ 
    return glob( 
     '{' . 
     $path . '/*,' . # Current Dir 
     $path . '/*/*,' . # One Level Down 
     $path . '/*/*/*' . # Two Levels Down, etc. 
     '}', GLOB_BRACE + GLOB_ONLYDIR); 
    } 
?> 

btw,感谢Doug对原函数的帮助!

回答

4

而不是使用glob(),我会建议使用DirectoryIterator类。

function get_dirs($path = '.') { 
    $dirs = array(); 

    foreach (new DirectoryIterator($path) as $file) { 
     if ($file->isDir() && !$file->isDot()) { 
      $dirs[] = $file->getFilename(); 
     } 
    } 

    return $dirs; 
} 
+0

嗨乔丹,这看起来不错,但我有一个问题。我从本地运行它,但得到一个致命的错误... 致命错误:未知的异常'UnexpectedValueException'消息'DirectoryIterator :: __构造(../ wp-content/themes/mytheme/images)[directoryiterator.--construct]:无法打开目录:没有这样的文件或目录'在C:\ xampplite \ htdocs \ wordpress \ wp-content \ themes \ mytheme \ functions.php:436 – 2009-12-15 17:18:21

+0

这是我的调用者。 $ mydir = get_dirs('../ wp-content/themes/mytheme/images'); – 2009-12-15 17:19:00

+0

尝试'$ mydir = get_dirs(realpath('../ wp-content/themes/mytheme/images'));'而不是。 – 2009-12-15 22:17:06

0

如果你只是想在当前文件夹的名称,作为回报,有一个平坦的阵列,可以extend一个RecursiveFilterIterator,只是在运行时收集的堆栈检查时,如果你想accept()它。在accept()方法中,你当然会跳过没有附加子迭代器的所有东西,所以你不必不必要地遍历不需要的部分。

class DirectoryStackIterator extends RecursiveFilterIterator 
{ 
    public static $stack = []; 

    public function __construct(FilesystemIterator $iterator) 
    { 
     parent::__construct($iterator); 
    } 

    public function getStack() 
    { 
     return self::$stack; 
    } 

    public function accept() 
    { 
     if ($this->hasChildren()) 
     { 
      foreach ($this->getChildren() as $c) 
      { 
       $dir = basename($c->getPath()); 
       $c->isDir() 
       && ! in_array($dir, self::$stack) 
        AND self::$stack[] = $dir; 
      } 
     } 

     return $this->hasChildren(); 
    } 
} 

这使得很容易定义什么是你想要的回报。 $cSPLFileInfo的一个实例,所以简单地参考一下。

$iterator = new DirectoryStackIterator(
    new RecursiveDirectoryIterator(
     __DIR__, 
     FilesystemIterator::FOLLOW_SYMLINKS 
     | FilesystemIterator::SKIP_DOTS 
    ) 
); 

然后我们附上RecursiveDirectoryIterator(延伸FilesystemIterator,然后延伸DirectoryIterator - 看看你得到了什么方法)和SKIP_DOTS,而是遵循符号链接。如果你不想要那个,请删除后面的那个。

最后我们只是遍历我们的迭代器迭代器而没有真正做任何事情。请记住,在最后使用分号(;)时,不要在每次事故时触发下一行的任何内容。

foreach ($iterator as $dir); 

收集我们的自定义堆栈则是很容易的:

var_dump($iterator->getStack()); 
相关问题