PHP使用SPL迭代器递归删除空目录

rdl*_*rey 6 php iterator

我正在努力解决如何使用SPL迭代器删除PHP中的空目录树.考虑以下目录结构,其中所有目录都是空的:

/ TOPDIR

  level1

       level2
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(
    '/topdir', RecursiveIteratorIterator::CHILD_FIRST
));

foreach ($it as $file) {
    if ($file->isDir()) {
        rmdir((string)$file);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是RecursiveIteratorIterator::CHILD_FIRST防止底层文件成为循环的一部分,我得到标准的Directory not emptyE_WARNING,因为level1不为空.

如何使用SPL迭代器递归删除空目录树?注意:我知道如何使用glob,scandir等等.请不要提供这些/类似功能的解决方案.

我觉得我必须在这里错过一些非常基本的东西......

d_i*_*ble 9

这是RecursiveIteratorIterator实际访问子目录.该RecursiveDirectoryIterator只提供手柄吧.

因此,您需要在以下位置设置CHILD_FIRST标志RecursiveIteratorIterator而不是RecursiveDirectoryIterator:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/topdir', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
);

foreach ($it as $file) {
    if ($file->isDir()) {
        rmdir((string)$file);
    }
}
Run Code Online (Sandbox Code Playgroud)

要防止警告,还要添加::SKIP_DOTS标志RecursiveDirectoryIterator