查找数组中重复的名称



我的问题是:我有一个数组,我在其中收集硬盘的所有文件,如:

$files = Array(
[0] => E:\folder1file1.mp4
[1] => E:\folder1folder1afile2.mp4
[2] => E:\folder2folder2afile3.avi
[3] => E:\folder2folder2afile4.avi
[4] => E:\folder2folder2afile5.avi
[5] => E:\folder2folder2afile6.avi
[6] => E:\folder2folder2afile7.avi
[7] => E:\folder2folder2afile8.mkv
[8] => E:\folder2folder2afile9.avi
[9] => E:\folder2folder2afile10.avi
[10] => E:\folder2folder2afile1.mp4
...
[2345] => E:\folder324folder324afolder324aafile5456789.mp4
)

在这个数组中,我想找到所有重复的名称,无论大小写和它们所在的文件夹,然后显示一个echo,以便在屏幕上打印如下:

file1.mp4 is duplicated in:
E:\folder1
E:\folder2\folder2a\

我试过了:


foreach($files as $ind => $c) {
$name = basename($c); 
$dups[] = $name;
}

foreach (array_count_values($dups) as $indd => $rty) {
if ($rty > 1) echo $indd . " is duplicated in: <br/>";
}

但是我不知道如何查看文件夹。

您需要跟踪文件所在的目录,因此首先使用文件名作为密钥构建目录列表…

$dups = [];
foreach ($files as $c) {
$dups[basename($c)][] = dirname($c);
}

第二次循环,如果有多个目录(count()为>1)然后回显出密钥(文件名)和目录(使用implode()将它们一起显示)…

foreach ($dups as $fileName => $rty) {
if (count($rty) > 1) {
echo $fileName . ' is duplicated in: ' . implode(', ', $rty) . PHP_EOL;
}
}

相关内容

  • 没有找到相关文章

最新更新