-4

嗨,我想将文件复制到目录中的所有文件夹

我的根文件夹树是

我想将根文件夹中的文件复制到每个目标文件夹

文件夹结构是

在此处输入图像描述

4

1 回答 1

1

由于您有一个静态文件夹结构,我建议将不同的子文件夹存储在一个数组中,然后将其循环到copy文件中

$rootpath = ".";
$destpaths = array("/Folder1/Subfolder1/AnotherSubFolder/Target/",
               "/Folder2/Subfolder1/AnotherSubFolder/Target/",
               "/Folder3/Subfolder1/AnotherSubFolder/Target/",
               "/Folder4/Subfolder1/AnotherSubFolder/Target/",
               "/Folder5/Subfolder1/AnotherSubFolder/Target/",
               "/Folder6/Subfolder1/AnotherSubFolder/Target/",
               "/FolderN/Subfolder1/AnotherSubFolder/Target/");
$file = '/example.txt';
$copyfrom = $rootpath . $file;

foreach($destpaths as $destpath)
{
    $copyto = $rootpath . $destpath . $file;
    if (!copy($copyfrom, $copyto)) {
        echo "failed to copy $file";
    }
}

正如 Aaron W. 所建议的那样 ,并且还使用glob-php来获取递归路径(folder1,folder2 ...),我将此代码和文件放置在同一个文件夹中,并将其放置在与文件夹 1、文件夹 2 相同的根路径中...

$rootpath = "..";
$frompath = ".";
$file = '/example.txt';
$tosubpath="/Subfolder1/AnotherSubFolder/Target/";
$copyfrom = $frompath . $file;

listdirs($rootpath,$copyfrom,$tosubpath,$file);


    function listdirs($dir,$copyfrom,$tosubpath,$file) {
        $dirs = glob($dir . '/*', GLOB_ONLYDIR);

    foreach($dirs as $destpath)
    {   

        $copyto = $destpath. $tosubpath . $file;
        if (!copy($copyfrom, $copyto)) {
            echo "failed to copy ".$copyfrom." to".$copyto."<br>";
        }else{
            echo $copyfrom." copied to".$copyto."<br>";
        }
    }
}
于 2013-01-08T12:19:37.607 回答