例如,我有一个构建。json文件如下。包含一个我用JSON创建的基本文件夹/文件结构。
{
"folders": [
{
"name": "folder-a",
"files": [
{
"name": "file-a.html"
},
{
"name": "file-b.html"
}
],
"folders": [
{
"name": "sub-folder-a",
"files": [
{
"name": "sub-file-a.html"
},
{
"name": "sub-file-b.html"
}
]
}
]
},
{
"name": "folder-b",
"files": [
{
"name": "file-a.html"
},
{
"name": "file-b.html"
}
]
}
]
}
现在我创建了下面的简单PHP代码,它可以循环遍历数组的第一部分。当然,如果我继续在第一个foreach中进行foreach循环,我就可以继续遍历数组。问题是,我不知道有多少文件夹/文件将在数组中。有什么办法能让我在不知道循环多少次的情况下继续循环吗?谢谢!
$json = file_get_contents('build.json');
$decode = json_decode($json);
foreach($decode as $key => $val){
foreach($val as $valKey => $data){
var_dump($data);
}
}
下面是一个使用递归的工作脚本:
$json = file_get_contents('build.json');
$folders = json_decode($json);
function buildDirs($folders, $path = null){
$path = $path == null ? "" : $path . "/";
foreach($folders as $key => $val){
mkdir($path.$val->name);
echo "Folder: " . $path . $val->name . "<br>";
if(!empty($val->files)){
foreach($val->files as $file){
//Create the files inside the current folder $val->name
echo "File: " . $path . $val->name . "/" . $file->name . "<br>";
file_put_contents($path . $val->name . "/". $file->name, "your data");
}
}
if(!empty($val->folders)){ //If there are any sub folders, call buildDirs again!
buildDirs($val->folders, $path . $val->name);
}
}
}
buildDirs($folders->folders); //Will build from current directory, otherwise send the path without trailing slash /var/www/here
记住要设置对根文件夹的权限
我还没有测试下面的代码,所以如果有bug请不要向我开枪,但是它说明了使用递归函数解决这个问题的基本过程。我们创建了一个函数,它将在当前级别创建一个文件夹,并向其中添加任何必要的文件。如果它有子文件夹,它将调用自己,但将路径传递给新的子文件夹级别。当没有更多的文件夹/文件要处理时,它就会停止,所以你不应该有无限递归的危险(像一个无限循环)。
/**
* @param $path string The base path in which $folder should be created
* @param $folder object An object that contains the content to be saved
*/
function createFileStructure( $path, $folder ) {
// create the current folder
$path = $path . '/' . $folder->name;
if ( mkdir( $path . $folder->name ) ) {
foreach ( $folder->files as $file ) touch( $path . '/' . $file->name );
}
// now handle subfolders if necessary
if ( isset( $folder->folders ) ) {
createFileStructure( $path, $folder->folders );
}
}
// now call the above recursive function
$path = __DIR__; // set the current directory as base
$json = file_get_contents('build.json');
createFileStructure( $path, json_decode( $json ) );