一般來說,你把代碼放在一個函數中,並使其遞歸:當它遇到一個目錄時,它會自己調用它來處理它的內容。事情是這樣的:
function processDirectoryTree($path) {
foreach (scandir($path) as $file) {
$thisPath = $path.DIRECTORY_SEPARATOR.$file;
if (is_dir($thisPath) && trim($thisPath, '.') !== '') {
// it's a directory, call ourself recursively
processDirectoryTree($thisPath);
}
else {
// it's a file, do whatever you want with it
}
}
}
在這種特殊情況下,你不需要這麼做,因爲PHP提供了現成的RecursiveDirectoryIterator
這個自動執行:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(getcdw()));
while($it->valid()) {
if ($it->getFilename() == 'abc.php') {
unlink($it->getPathname());
}
$it->next();
}
來源
2013-02-12 09:29:08
Jon
HTTP://www.kerstner。 at/en/2011/12/recursively-delete-files-using-php/ – Stefan 2013-02-12 09:30:48