假設有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);