我正在尝试将一些文件从目录移动到另一个目录,我发现这个脚本here但是这个脚本循环遍历所有文件,我想要的是改变这个脚本只循环50个文件。代码:
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
答案 0 :(得分:0)
也许我没弄清楚,但你考虑过一个简单的计数吗?
$i = 0;
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if($i < 50) {
if (copy($source.$file, $destination.$file)) {
unlink($source.$file); //move unlink here to avoid a second loop
}
else{
break;
}
}
$i++;
}
答案 1 :(得分:0)
使用for循环,而不是foreach循环。
在这种情况下,for
循环更为明智,因为每次运行此代码时,您都会循环一定次数。
foreach
循环用于遍历整个数组或对象。
这是一种目的感。当另一个程序员查看你的代码时,他们会立即知道你循环50次,而不是循环整个数组。
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
for ($i=0; $i < 50; $i++) {
$file = $files[$i];
if( !$file )
break;
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
答案 2 :(得分:0)
您可以设置count
并在达到50次时停止循环:
$count = 0;
$maxiterations = 50;
foreach ($files as $file) {
if ($count < $maxiterations) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
$i++;
}
else {
break;
}
}