php 如何生成二级目录json,使用PHP根据已解码的JSON创建文件夹/文件结构
例如,我下面有一個(gè)build.json文件.包含我在JSON中創(chuàng)建的基本文件夾/文件結(jié)構(gòu).
{
"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"
}
]
}
]
}
現(xiàn)在,我在下面創(chuàng)建了簡(jiǎn)單的PHP代碼,可以遍歷數(shù)組的第一部分.然后,當(dāng)然,如果我繼續(xù)在第一個(gè)foreach中進(jìn)行foreach循環(huán),則可以繼續(xù)遍歷數(shù)組.問(wèn)題是我不知道陣列中將有多少個(gè)文件夾/文件.關(guān)于如何不知道循環(huán)多少就可以繼續(xù)循環(huán)的任何想法?謝謝!
$json = file_get_contents('build.json');
$decode = json_decode($json);
foreach($decode as $key => $val){
foreach($val as $valKey => $data){
var_dump($data);
}
}
解決方法:
這是一個(gè)使用遞歸的工作腳本:
$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
記住要對(duì)根文件夾設(shè)置正確的權(quán)限.
標(biāo)簽:loops,arrays,json,php,recursion
來(lái)源: https://codeday.me/bug/20191027/1947620.html
總結(jié)
以上是生活随笔為你收集整理的php 如何生成二级目录json,使用PHP根据已解码的JSON创建文件夹/文件结构的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: django mysql connect
- 下一篇: 湿疹严重吗