【发布时间】:2010-05-08 05:51:57
【问题描述】:
我正在使用 PHP,我需要编写如下脚本:
我要比较两个文件夹结构 并参考源文件夹 I 想要删除所有文件/文件夹 存在于其他目标文件夹中 参考源中不存在的 文件夹,我该怎么做?
已编辑:
$original = scan_dir_recursive('/var/www/html/copy2');
$mirror = scan_dir_recursive('/var/www/html/copy1');
function scan_dir_recursive($dir) {
$all_paths = array();
$new_paths = scandir($dir);
foreach ($new_paths as $path) {
if ($path == '.' || $path == '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $path;
if (is_dir($path)) {
$all_paths = array_merge($all_paths, scan_dir_recursive($path));
} else {
$all_paths[] = $path;
}
}
return $all_paths;
}
foreach($mirror as $mirr)
{
if($mirr != '.' && $mirr != '..')
{
if(!in_array($mirr, $original))
{
unlink($mirr);
// delete the file
}
}
}
上面的代码显示了我做了什么.. 在这里,我的 copy1 文件夹包含比 copy2 文件夹更多的文件,因此我需要删除这些额外的文件。
已编辑: 下面给出的输出是原始镜像的数组和两者的差异..
Original Array
(
[0] => /var/www/html/copy2/Copy (5) of New Text Document.txt
[1] => /var/www/html/copy2/Copy of New Text Document.txt
)
Mirror Array
(
[0] => /var/www/html/copy1/Copy (2) of New Text Document.txt
[1] => /var/www/html/copy1/Copy (3) of New Text Document.txt
[2] => /var/www/html/copy1/Copy (5) of New Text Document.txt
)
Difference Array
(
[0] => /var/www/html/copy1/Copy (2) of New Text Document.txt
[1] => /var/www/html/copy1/Copy (3) of New Text Document.txt
[2] => /var/www/html/copy1/Copy (5) of New Text Document.txt
)
当我迭代循环以删除差异数组时,必须根据显示的输出删除所有文件.. 我该如何纠正这个.. 删除循环如下所示。
$dirs_to_delete = array();
foreach ($diff_path as $path) {
if (is_dir($path)) {
$dirs_to_delete[] = $path;
} else {
unlink($path);
}
}
while ($dir = array_pop($dirs_to_delete)) {
rmdir($dir);
}
【问题讨论】:
-
我试图解释我的评论中出了什么问题。昨晚我太累了,无法解决我一开始就知道会出错的事情,对不起!我的帖子现在更新了一个更好的答案。