我正在尝试查找文件大小完全相同的文件,并将文件保持最新的文件大小,然后删除其他文件。
到目前为止,我正在浏览所有文件并获取最新的更改文件。
编辑我的代码当前代码删除了很多,但是仍然有3个文件大小相同的文件没有被正确删除(保留最新更改的一个删除其他文件)。
$files = glob($currentDir.'\*.jpg', GLOB_NOSORT);
$count = count($files);
$itemsToRemove = [];
for ($i = 0; $i < $count - 1; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
// compare $z[$i] with $z[$j]...
if(filesize($files[$i]) == filesize($files[$j])) {
if(is_file($files[$j])) {
$itemsToRemove[] = $files[$j];
}
}
}
}
foreach($itemsToRemove as $item) {
if(is_file($item)) {
unlink($item);
}
}
但是输出错误。它仍然显示一些重复的文件,并带有一些文件大小。我认为我将它们比较错了,我需要将每个值与数组中的所有其他值进行比较。
我想您的任务可以解决,例如:
$curSize = false;
foreach ($files as $file) {
if ($curSize === false || filesize($file) !== $curSize) {
$curSize = filesize($file);
} else {
unlink($file);
}
}
我不确定这是否是您想要的,但希望您能从中获得帮助! :-)
<?php
$files = glob('*.jpg', GLOB_NOSORT);
//Get filetimes and only include unique filetimes (array_unique below)
$filetimes_arr = array_map('filemtime', $files);
array_multisort($filetimes_arr, SORT_NUMERIC,
SORT_DESC, $files); //latest changed files 0,1...
//This would include only unique filetimes but still having same key as $files
$uniqe_times = array_unique($filetimes_arr);
/*
example:
($files)
0 => string 'brannebrona-e1536697041347-144x150.jpg' (length=38)
1 => string 'brannebrona-e1536697041347-150x150.jpg' (length=38)
2 => string 'brannebrona-e1536697041347-250x150.jpg' (length=38)
3 => string 'brannebrona-e1536697041347-288x300.jpg' (length=38)
4 => string 'brannebrona-e1536697041347-393x311.jpg' (length=38)
5 => string 'brannebrona-e1536697041347-649x250.jpg' (length=38)
6 => string 'brannebrona-e1536697041347-649x580.jpg' (length=38)
7 => string 'brannebrona-e1536697041347.jpg' (length=30)
8 => string 'brannebrona-e1536696975180.jpg' (length=30)
9 => string 'brannebrona-e1536696959513.jpg' (length=30)
10 => string 'brannebrona-1565x580.jpg' (length=24)
11 => string 'brannebrona-250x150.jpg' (length=23)
12 => string 'brannebrona-393x311.jpg' (length=23)
13 => string 'brannebrona-1024x450.jpg' (length=24)
14 => string 'brannebrona-1180x250.jpg' (length=24)
15 => string 'brannebrona-150x150.jpg' (length=23)
16 => string 'brannebrona-150x66.jpg' (length=22)
17 => string 'brannebrona-300x132.jpg' (length=23)
18 => string 'brannebrona-768x337.jpg' (length=23)
19 => string 'brannebrona.jpg' (length=15)
($uniqe_times) (key intact with $files)
0 => int 1536697041
8 => int 1536696975
9 => int 1536696959
10 => int 1536696759
13 => int 1536696758
19 => int 1536696757
(0-7 has the same filesize)
(10-12 has the same filesize)
(13-18 has the same filesize)
Go through the unique filesize array
and include the actual file you want
*/
$use_files = array();
foreach($uniqe_times as $key=>$t) {
$use_files[] = $files[$key];
}
//Go head and use the array $use_files