【问题标题】:How to loop throught folders and subfolders and create using Laravel?如何遍历文件夹和子文件夹并使用 Laravel 创建?
【发布时间】:2018-11-23 15:50:15
【问题描述】:

您好,在创建嵌套文件夹方面需要帮助。

我目前有一个名为 images 的文件夹,我想克隆这些文件夹并将其保存在另一个文件夹调用备份中。并且备份只会在用户单击备份时发生。

例如:

- Images
 - Car
    - A
      - A1
        - A1-1
      - A2
    - B
 - Van

如何编写代码以创建文件夹?

目前我已经这样做了,我该怎么做呢?

public function sync(Request $request)
{
    $arr = [];
    $folderToSync = $request->input('folderName');

    $originalPath = public_path($folderToSync);
    $newFolderPath = public_path('S3/'.$folderToSync);

    $this->createFolder($newFolderPath); // create the selected folder

    $directories = $this->getAllFolders($originalPath); // getting all folders under the original path

    $this->folder($directories, $newFolderPath, $originalPath);

    dd('end');
}

public function createFolder($path)
{
    if (!is_dir($path)) {
        @mkdir($path, 0777, true);
    }
}

public function folder($directories, $newFolderPath, $originalPath)
{
    foreach ($directories as $directory) {
        $newPath = $newFolderPath.'/'.$directory;
        $oriPath = $originalPath.'/'.$directory;

        $this->createFolder($newPath);
        $subFolders = $this->getAllFolders($oriPath);

        if ($subFolders) {
            $this->subfolder($subFolders, $newPath);
        }
    }
}

public function subfolder($directories, $path)
{
    foreach ($directories as $directory) {
        $this->createFolder($path.'/'.$directory);
    }
}

public function getAllFolders($path)
{
    return array_map('basename', \File::directories($path));
}

public function getAllFiles($path)
{
    return;
}

但它没有创建子文件夹。怎么修改?

我每周都会运行代码,我还想检查哪些文件夹已创建,哪些尚未创建。如果该文件夹不存在,则创建该文件夹。

【问题讨论】:

标签: php laravel


【解决方案1】:

我想看看 Laravel 文档中的存储 API:https://laravel.com/docs/5.7/filesystem#directories

获取文件夹和子文件夹:

// Recursive...
$directories = Storage::allDirectories($directory);

创建一个新目录:

Storage::makeDirectory($directory);

存储文件:

Storage::put('file.jpg', $contents);

Storage::put('file.jpg', $resource);

put 方法将获取文件内容或资源。

不要忘记包含Storage 外观:

use Illuminate\Support\Facades\Storage;

【讨论】:

  • 我怎么能把这个数组中的文件夹除外 我试试 Arr::except($directories , ['thumbnails']);但没有用。并将缩略图文件夹中的所有子文件夹归还给我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
相关资源
最近更新 更多