PHP如何将多个文件复制到多个文件夹

时间:2013-06-07 10:03:51

标签: php

我正在处理复制文件,我可以将一个文件复制到多个文件夹,但是在将多个文件复制到多个文件夹时出现问题。

我的代码:

$sourcefiles = array('./folder1/test.txt', './folder1/test2.txt');

$destinations = array('./folder2/test.txt', './folder2/test2.txt');

//do copy

foreach($sourcefiles as $source) {

    foreach($destinations as $des){
        copy($source, $des);
    }

}

但这段代码不起作用!

你能给我一个解决方案:(

感谢您的帮助!

5 个答案:

答案 0 :(得分:5)

您目前所做的是循环源文件,在第一次尝试中是“test.txt”,然后循环目标数组并执行复制功能2次:

第一次使用folder1 / test.txt进行迭代

  • copy(“folder1 / test.txt”,“folder2 / test.txt”);
  • copy(“folder1 / test.txt”,“folder2 / test2.txt”;

第二次使用folder1 / test2.txt进行迭代:

  • copy(“folder1 / test2.txt”,“folder2 / test.txt”);
  • copy(“folder1 / test2.txt”,“folder2 / test2.txt”;

最后,您使用$ source数组中的最后一个文件覆盖了这两个文件。因此“folder2”中的两个文件都包含test2.txt

的数据

您正在寻找的是:

foreach($sourcefiles as $key => $sourcefile) {
  copy($sourcefile, $destinations[$key]);
}

$ sourcefile等于上面例子中的$ sourcefiles [$ key]。

这是基于PHP自动为您的值分配键的事实。 $ sourcefiles = array('file1.txt','file2.txt');可以用作:

$sourcefiles = array(
  0 => 'file1.txt',
  1 => 'file2.txt'
);

另一种选择是在for循环中使用其中一个数组的长度,它以不同的方式执行相同的操作:

for ($i = 0; $i < count($sourcefiles); $i++) {
    copy($sourcefiles[$i], $destinations[$i]);
}

答案 1 :(得分:1)

我认为你要做的就是这个;

for ($i = 0; $i < count($sourcefiles); $i++) {
    copy($sourcefiles[$i], $destinations[$i]);
}

您当前的代码将覆盖以前的副本。

答案 2 :(得分:1)

假设你有相同数量的文件:

// php 5.4, lower version users should replace [] with array() 
$sources = ['s1', 's2'];
$destinations = ['d1', 'd2'];

$copy = [];

foreach($sources as $index => $file) $copy[$file] = $destinations[$index];


foreach($copy as $source => $destination) copy($source, $destination);

答案 3 :(得分:1)

由于两个数组都需要相同的索引,因此请使用for循环。

for ($i = 0; $i < count($sourcefiles); $i++) {
    //In here, $sourcefiles[$i] is the source, and $destinations[$i] is the destination.
}

答案 4 :(得分:0)

当然不是。您的嵌套循环正在复制文件,以至于它们必须覆盖以前的文件副本。我认为你需要使用更简单的解决方案。在嵌套循环中复制没有任何意义。

如果你有源文件和目标文件,那么我建议一个循环:

$copyArray = array(
    array('source' => './folder1/test.txt', 'destination' => './folder2/test.txt'),
    array('source' => './folder1/test.txt', 'destination' => './folder2/test.txt'));

foreach ($copyArray as $copyInstructions)
{
    copy($copyInstructions['source'], $copyInstructions['destination']);
}

但请确保您的目标文件名不同!