0

我正在尝试将一些文件从一个目录移动到另一个目录,我在这里找到了这个脚本,但是这个脚本循环了所有文件,我想要改变这个脚本只循环 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);
}
4

3 回答 3

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++;
}
于 2013-03-15T06:26:10.367 回答
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);
}
于 2013-03-15T06:26:30.287 回答
0

您可以设置 acount并在达到 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;
    }
}
于 2013-03-15T06:26:55.223 回答