假设有2个目录我的服务器上:如何在各种目录中检测具有相同名称的文件?
/xyz/public_html/a/
/xyz/public_html/b/
二者均包括许多文件。我如何检测这两个文件夹在name
和file_extension
方面共同的文件。这个程序将在PHP中实现。有什么建议么?
假设有2个目录我的服务器上:如何在各种目录中检测具有相同名称的文件?
/xyz/public_html/a/
/xyz/public_html/b/
二者均包括许多文件。我如何检测这两个文件夹在name
和file_extension
方面共同的文件。这个程序将在PHP中实现。有什么建议么?
使用FileSystemIterator
,你可能会做这样的事情......
<?
$it = new FilesystemIterator('/xyz/public_html/a/');
$commonFiles = array();
foreach ($it as $file) {
if ($file->isDot() || $file->isDir()) continue;
if (file_exists('/xyz/public_html/b/' . $file->getFilename())) {
$commonFiles[] = $file->getFilename();
}
}
基本上,你通过一个目录下的所有文件必须循环,并看看是否在其他目录中存在任何相同名字的文件。请记住,文件名包含扩展名。
如果只是两个目录,你可以使用类似的merge sort,你已经整理项目的两个列表合并算法的算法,同时走他们,而比较当前的项目:
$iter1 = new FilesystemIterator('/xyz/public_html/a/');
$iter2 = new FilesystemIterator('/xyz/public_html/b/');
while ($iter1->valid() && $iter2->valid()) {
$diff = strcmp($iter1->current()->getFilename(), $iter2->current()->getFilename());
if ($diff === 0) {
// duplicate found
} else if ($diff < 0) {
$iter1->next();
} else {
$iter2->next();
}
}
另一种解决方案将让你把每个目录项使用数组键的唯一性到一个数组作为键,然后检查是否有其他目录的每个项目,如果这样的密钥存在:
$arr = array();
$iter1 = new FilesystemIterator('/xyz/public_html/a/');
foreach ($iter1 as $item) {
$arr[$item->getFilename()] = true;
}
$iter2 = new FilesystemIterator('/xyz/public_html/a/');
foreach ($iter2 as $item) {
if (array_key_exists($item->getFilename(), $arr)) {
// duplicate found
}
}
如果你只是想找出哪些是共同的,你可以很容易地使用scandir两次,并找到共同点,例如:
//Remove first two elements, which will be the constant . and .. Not a very sexy solution
$filesInA = array_shift(array_shift(scandir('/xyz/publichtml/a/')));
$filesInB = array_shift(array_shift(scandir('/xyz/publichtml/b/')));
$filesInCommon = array_intersect($filesInA, $filesInB);