您可以创造自己的GlobMarkIterator
优势:
- 将结束斜杠返回到目录,就像
GLOB_MARK
- 无需使用
array_map
withstrval
将其转换为字符串
- 没有额外的
foreach
循环is_dir
- 还是和原来一样快
- 是的,我知道我作弊了
例子
$ri = new RecursiveIteratorIterator(new GlobMarkIterator('./', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS), RecursiveIteratorIterator::SELF_FIRST);
$files = array_values(iterator_to_array($ri));
echo "<pre>";
print_r($files);
输出
Array
(
[0] => ./test/backups/ <----------- Note ending slash
[1] => ./test/CSV/
[2] => ./test/CSV/abc.csv
[3] => ./test/final/
[4] => ./test/thumb/
[5] => ./test/thumb/a.png
[6] => ./test/thumb/s.svg
[7] => ./test/thumb/sample.svg
)
奖励问题:有没有办法只获取目录(递归)?
这应该是另一个问题,但都是一样的......我希望你不要满意,并为此提供赏金
解决方案 :
$ri = new RecursiveIteratorIterator( new GlobMarkDirectory('./test'), RecursiveIteratorIterator::SELF_FIRST);
$dir = array_values(iterator_to_array($ri));
echo "<pre>";
print_r($dir);
输出
Array
(
[0] => ./test/backups/
[1] => ./test/CSV/
[2] => ./test/final/
[3] => ./test/thumb/
)
使用的类
GlobMarkIterator
class GlobMarkIterator extends RecursiveDirectoryIterator {
function current() {
return $this->isDir() ? $this->getPathname() . "/" : $this->getPathname();
}
}
GlobMarkDirectory
班级
class GlobMarkDirectory extends RecursiveFilterIterator {
public function __construct($path) {
parent::__construct(new GlobMarkIterator($path, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS));
}
public function accept() {
return $this->getInnerIterator()->isDir();
}
public function getChildren() {
return new GlobMarkDirectory($this->getInnerIterator()->getPathname());
}
}
编辑..如果您不关心并且由于速度和开销而empty dir
不想使用这里是另一种解决方案isDir
解决方案
$ri = new RecursiveIteratorIterator(new GlobMarkFastDirectory (__DIR__), RecursiveIteratorIterator::SELF_FIRST);
$dir = array_values(array_unique(iterator_to_array($ri)));
GlobMarkFastDirectory
class GlobMarkFastDirectory extends RecursiveDirectoryIterator {
function current() {
return dirname($this->getPathname()) ."/";
}
}