如何使用SPL检索完整目录树? [英] How can I retrieve the full directory tree using SPL?

查看:150
本文介绍了如何使用SPL检索完整目录树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用SPL(可能使用RecursiveDirectoryIteratorRecursiveIteratorIterator)检索完整目录树?

How can I retrieve the full directory tree using SPL, possibly using RecursiveDirectoryIterator and RecursiveIteratorIterator?

推荐答案

默认情况下,RecursiveIteratorIterator将使用LEAVES_ONLY作为

By default, the RecursiveIteratorIterator will use LEAVES_ONLY for the second argument to __construct. This means it will return files only. If you want to include files and directories (at least that's what I'd consider a full directory tree), you'd have to do:

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

,然后可以在其上foreach.如果要返回目录树而不是输出目录树,则可以将其存储在数组中,例如

and then you can foreach over it. If you want to return the directory tree instead of outputting it, you can store it in an array, e.g.

foreach ($iterator as $fileObject) {
    $files[] = $fileObject;
    // or if you only want the filenames
    $files[] = $fileObject->getPathname();
}

您还可以通过执行以下操作来创建不包含foreach$fileObjects数组:

You can also create the array of $fileObjects without the foreach by doing:

$files[] = iterator_to_array($iterator);

如果只希望返回目录,请像这样在$iterator上通过foreach

If you only want directories returned, foreach over the $iterator like this:

foreach ($iterator as $fileObject) {
    if ($fileObject->isDir()) {
        $files[] = $fileObject;
    }
}

这篇关于如何使用SPL检索完整目录树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆