我有一个文件夹,里面装满了空文件夹和完整文件夹。
我想遍历所有它们,弄清楚它们是否为空,如果是,则将其删除。我已经看到了一些适用的问题,但是我无法找出整体解决方案:
使用新的PHP5函数,必须有一些简单的确定方法来做到这一点?
有点像(充满错误的伪代码)
<?php
$dir = new DirectoryIterator('/userfiles/images/models/');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
if(!(new \FilesystemIterator($fileinfo))->valid()) {
rmdir($fileinfo);
}
}
}
?>
这应该为您工作:
在这里,我只是使用glob()
(PHP 4> = 4.3.0,PHP 5)从特定路径获取所有目录。然后,我遍历每个目录并检查它是否为空。
如果为空,则用rmdir()
其他方式将其删除,然后检查其中是否还有其他目录,并使用新目录调用该函数
<?php
function removeEmptyDirs($path, $checkUpdated = false, $report = false) {
$dirs = glob($path . "/*", GLOB_ONLYDIR);
foreach($dirs as $dir) {
$files = glob($dir . "/*");
$innerDirs = glob($dir . "/*", GLOB_ONLYDIR);
if(empty($files)) {
if(!rmdir($dir))
echo "Err: " . $dir . "<br />";
elseif($report)
echo $dir . " - removed!" . "<br />";
} elseif(!empty($innerDirs)) {
removeEmptyDirs($dir, $checkUpdated, $report);
if($checkUpdated)
removeEmptyDirs($path, $checkUpdated, $report);
}
}
}
?>
(PHP 4 >= 4.3.3, PHP 5)
removeEmptyDirs — Removes empty directory's
void removeEmptyDirs(字符串$ path [,bool $ checkUpdated = false [,bool $ report = false]])
The removeEmptyDirs() function goes through a directory and removes every empty directory
path
The Path where it should remove empty directorys
checkUpdated
If it is set to TRUE it goes through each directory again if one directory got removed
report
If it is set to TRUE the function outputs which directory get's removed
None
举个例子:
如果这样$checkUpdated
的TRUE
结构被完全删除:
- dir
| - file.txt
| - dir
| - dir
结果:
- dir
| - file.txt
如果FALSE
默认情况下,结果将是:
- dir
| - file.txt
| - dir //See here this is still here
如果$report
是TRUE
你会得到这样的输出:
test/a - removed!
test/b - removed!
test/c - removed!
否则你没有输出
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句