循环目录并保存数据

时间:2016-07-14 14:59:58

标签: php arrays directory

我有一个名为images的目录。让我们说道路是

somepath.com/images/

在我的images目录中有许多文件夹。所以我要说我有

somepath.com/images/folder1
somepath.com/images/folder2

在每个文件夹中都有许多图像。所以我要说我有

somepath.com/images/folder1/img1.png
somepath.com/images/folder1/img2.png
somepath.com/images/folder2/img1.png
somepath.com/images/folder2/img2.png

我正在尝试构建一个包含所有这些数据的数组。我希望数组看起来像这样

array:2 [▼
  "directories" => array:1 [▼
    "Name" => "folder1"
  ]
  "files" => array:14 [▼
    0 => array:1 [▼
      "Name" => "img1.png"
    ]
    2 => array:1 [▼
      "Name" => "img2.png"
    ]
  ]
]
array:2 [▼
  "directories" => array:1 [▼
    "Name" => "folder2"
  ]
  "files" => array:14 [▼
    0 => array:1 [▼
      "Name" => "img1.png"
    ]
    2 => array:1 [▼
      "Name" => "img2.png"
    ]
  ]
]

这样,我可以看到有一个文件夹1,里面是img1和img2。为了生成这个数组,我目前正在扫描基目录以获取文件夹名称。然后我循环文件夹以获取文件名。这就是我目前所拥有的

$data = array();
$directories = scandir("somepath.com/images/");

foreach($directories as $directory){
    if($directory=='.' or $directory=='..' ){
        continue;
    } else{
        $data["directories"] = array(
            "Name" => $directory
        );

        $dirFiles = scandir("somepath.com/images/" . $directory);
        foreach($dirFiles as $file){
            if($file=='.' or $file=='..' ){
                continue;
            } else {
                $data["files"][] = array(
                    "Name" => $file
                );
            }
        }
    }
}

我目前遇到的问题是第一个目录数据被覆盖。另外,我剩下的数组似乎有了folder2的所有4个图像。我怎样才能改变我拥有的东西 为了产生所需的输出?

由于

2 个答案:

答案 0 :(得分:2)

虽然结构略有不同,但使用数组索引作为文件夹名称,您可以使用以下代码:Deep recursive array of directory structure in PHP  这将产生一个像:

的数组
array:2 [
  "folder1" => array:2 [
    "img1.png",
    "img2.png"
  ],
  "folder2" => array:2 [
    "img1.png",
    "img2.png"
  ]
]

代码也将遍历多个子目录,因此给定第一个块中的结构,它也会像第二个块一样创建结果:

somepath.com/images/folder1/img1.png
somepath.com/images/folder1/img2.png
somepath.com/images/folder1/subfolder1/img1.png
somepath.com/images/folder1/subfolder1/img2.png
somepath.com/images/folder2/img1.png
somepath.com/images/folder2/img2.png
somepath.com/images/folder2/subfolder1/img1.png
somepath.com/images/folder2/subfolder1/img2.png

- 收益率:

array:2 [
  "folder1" => array:3 [
    "subfolder1" => array:2 [
      "img1.png",
      "img2.png"
    ]
    "img1.png",
    "img2.png"
  ],
  "folder2" => array:3 [
    "subfolder1" => array:2 [
      "img1.png",
      "img2.png"
    ]
    "img1.png",
    "img2.png"
  ]
]

答案 1 :(得分:1)

您可以查看此处找到的use课程。也许它会为你做伎俩。您可以将它包含在项目中并像以下一样使用它:

FolderScanner