php 如何生成二级目录json,使用PHP根据已解码的JSON创建文件夹/文件结构
例如,我下面有一個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
總結
以上是生活随笔為你收集整理的php 如何生成二级目录json,使用PHP根据已解码的JSON创建文件夹/文件结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django mysql connect
- 下一篇: nginx php iconv,Ngin