0

1 つのファイルを複数のフォルダにコピーできますが、複数のファイルを複数のフォルダにコピーするときに問題が発生します。

私のコード:

$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);
    }

}

しかし、このコードは機能しません!

解決策を教えてください:(

助けてくれてありがとう!

4

5 に答える 5

5

あなたが現在行っていることは、最初の反復で「test.txt」であるソースファイルをループしてから、宛先配列をループしてコピー機能を2回実行することです:

folder1/test.txt を使用した最初の反復

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

folder1/test2.txt を使用した 2 回目の反復:

  • 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'
);

もう 1 つのオプションは、配列の 1 つの長さを for ループで使用することです。これは同じことを別の方法で行います。

for ($i = 0; $i < count($sourcefiles); $i++) {
    copy($sourcefiles[$i], $destinations[$i]);
}
于 2013-06-07T10:11:53.597 に答える
1

あなたがやろうとしていることはこれだと思います。

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

現在のコードは以前のコピーを上書きします。

于 2013-06-07T10:10:48.870 に答える
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);
于 2013-06-07T10:10:56.990 に答える
1

両方の配列に同じインデックスが必要なため、forループを使用します。

for ($i = 0; $i < count($sourcefiles); $i++) {
    //In here, $sourcefiles[$i] is the source, and $destinations[$i] is the destination.
}
于 2013-06-07T10:11:22.183 に答える
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']);
}

ただし、宛先ファイル名が異なることを確認してください!

于 2013-06-07T10:08:13.407 に答える