例如,我下面有一个build.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 . "
";
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 . "
";
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
记住要对根文件夹设置正确的权限.
标签:loops,arrays,json,php,recursion
来源: https://codeday.me/bug/20191027/1947620.html