我试图创建一个递归读取所有文件夹并将其插入多维数组的脚本。
所以我创建了一个测试这个脚本的示例路径。我的文件夹:
TesteFolder
-1
-11
-12
-13
我期望在json输出:
{
"name": "1",
"pathTo": "TestFolder/1",
"children": [{
"name": "11",
"pathTo": "TestFolder/11",
},
{
"name": "12",
"pathTo": "TestFolder/12",
},
{
"name": "13",
"pathTo": "TestFolder/13",
}
]
}
我试过了:
$folders = array();
function listFolder($dir,$folders){
$prov = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
$prov[] = $ff;
if(is_dir($dir.'/'.$ff)) {
$folders['children'] = listFolder($dir.'/'.$ff,$prov);
}
}
}
return $folders;
}
$arr = listFolder('TesteJSON',$folders);
echo json_encode($arr);
我该怎么做?
答案 0 :(得分:1)
你的递归搞砸了。你可以在每次递归中返回数组,就像这样。
function listFolder($dir) {
$result = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if($ff != '.' && $ff != '..') {
$info = array("name" => $ff, "pathTo" => $dir.'/'.$ff);
if(is_dir($dir.'/'.$ff)) {
$info['children'] = listFolder($dir.'/'.$ff);
}
$result[] = $info;
}
}
return $result;
}
请注意,代码未经过测试,仅用于演示简单的"返回值"递归。另请注意,文件夹的符号链接可能会导致循环引用,这可能会导致无限递归,但这只是猜测,因为我目前还没有深入PHP环境。
答案 1 :(得分:0)
我对此的看法:
$folders = array();
function listFolder($dir,$folders){
$prov = array();
$ffs = scandir($dir);
$provv = array();
if (empty($folders)){//parent folder
$folders['name'] = $dir;
$folders['pathTo'] = $dir;
}
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
$prov['name'] = $ff;
$prov['pathTo'] = $dir.'/'.$ff;
$provv[] = $prov;
if(is_dir($dir.'/'.$ff)) {
$folders['children'] = listFolder($dir.'/'.$ff,$provv);
}
}
}
return $folders;
}
$arr = listFolder('test',$folders);
echo json_encode($arr);