这应该适合你:
1。我使用glob() 来获取目录中与模式匹配的所有文件
2。我用 array_chunk() 从所有文件的数组中创建了 10 个块。所以我转换了数组,例如Array ( [0] => ... [2000] => ...) 到一个看起来像这样的数组:Array ( [0] => Array ( [0] => ... [9] => ...) )
3。我用mkdir()创建了尽可能多的文件夹
4。最后我用rename()移动了目录中的所有文件
<?php
//Configuration
$folderPattern = "part";
$chunkSize = 10;
$path = "images/";
//get images
$files = glob($path . "*.*");
$chunks = array_chunk($files, $chunkSize);
//create folders
for($i = 1; $i <= count($chunks); $i++) {
if(!file_exists($path . $folderPattern . $i))
mkdir($path . $folderPattern . $i, 0700);
}
//move images
for($i = 1; $i <= count($chunks); $i++) {
for($x = 0; $x < count($chunks[$i-1]); $x++) {
rename($path . basename($chunks[$i-1][$x]), $path . $folderPattern . $i . "/" . basename($chunks[$i-1][$x]));
echo $path . basename($chunks[$i-1][$x]) . " -> " . $path . $folderPattern . $i . "/" . basename($chunks[$i-1][$x]) . "<br />";
}
}
?>
根据您对基本 php 的了解,您可能需要了解以下内容:
答案测试:
- 拥有 10000 张图片
- 与答案中的配置相同
- 图像大小:31'503 字节
- 执行时间:15-17 秒(平均:16.189925909042 秒)
编辑:
要更改文件夹结构:
X 个文件夹,包含 10 张图片
到:
10 个包含 X 张图片的文件夹
此脚本将 X 文件夹转换为 X/10 文件夹,例如8139 -> 813 个文件夹。所以如果你想转换 8139 -> 813 运行 2x,如果你想 8139 -> 81 运行 3x。
注意:如果文件已经存在,例如/images/part1/xy.jpg 并且您想将文件移动到此文件夹中,它会自动将 - TEMP-[random number] 附加到名称中,这样它就不会丢失。例如,如果您现在想将文件:/images/partXY/xy.jpg 从上方移动到文件夹中,则文件将重命名为:/images/part1/xy.jpg - TEMP-906222766。因此,您可以轻松发现这些文件并将其重命名为您想要的名称。
(如果您想对此代码进行完整解释,请在 cmets 中告诉我)
<?php
//Since it can take a few seconds more than 30 and default is (mostly) 30
set_time_limit(120);
//Configuration
$path = "images/";
$chunkSize = 10;
//Get all dirs
$dirs = glob($path . "*");
//Get all files
foreach($dirs as $dir)
$files[] = glob($dir . "/*.*");
//Define MAX folders
$files = array_chunk($files, $chunkSize);
foreach($files as $key => $innerArray) {
$baseFolder = dirname(str_replace($path, "", array_column($innerArray, 0)[0]));
for($i = 1; $i < count($innerArray); $i++) {
foreach($files[$key][$i] as $file) {
if(file_exists($path . $baseFolder . "/" . basename($file)))
rename($file, $path . $baseFolder . "/" . basename($file) . " - TEMP-" . mt_rand());
else
rename($file, $path . $baseFolder . "/" . basename($file));
echo $file . " -> " . $path . $baseFolder . "/" . basename($file) . "<br />";
}
//Delete dir
rmdir($path . str_replace($path, "", dirname($files[$key][$i][0])));
echo "<br /><br />Removed: " . $path . str_replace($path, "", dirname($files[$key][$i][0])) . "<br /><br />";
}
}
?>
答案测试:
- 拥有 10'000 张图片 | à 1'000 个文件夹,例如每个文件夹 10 张图片
- 与答案中的配置相同
- 图像大小:31'503 字节
- 脚本调用:2 次:
- 1'000 个文件夹 -> 100 个
- 100 个文件夹 -> 10 个
- 执行时间:29-33 秒(平均:31.29639005661 秒)