【发布时间】:2021-12-14 15:33:43
【问题描述】:
我想在 php.ini 中创建一个文件夹树数组。我编码了一些东西,它几乎完成了,但是有一些问题。
所以,所有文件和文件夹都应该在相同的 json 中,因为它们在文件夹中。这是我的代码:
function getDirContents($dir, &$results = array(), $counter = 0 ) {
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = array('name'=>$path,'type'=>'file');
} else if ($value != "." && $value != "..") {
$results[] = array('name'=>$path,'type'=>'folder','subfolders'=>array());
getDirContents($path, $results[count($results)]['subfolders']);
}
}
return $results;
}
print_r(json_encode(getDirContents('./')));
结果如下。但它在不同的地方有子文件夹标签。例如;子文件夹 test4 应该在 test2 子文件夹中,但它是 test2 文件夹中的区。
[
{
"name":"C:\\xampp\\htdocs\\test\\test.php",
"type":"file"
},
{
"name":"C:\\xampp\\htdocs\\test\\test.txt",
"type":"file"
},
{
"name":"C:\\xampp\\htdocs\\test\\test1",
"type":"folder",
"subfolders":[
]
},
{
"subfolders":[
{
"name":"C:\\xampp\\htdocs\\test\\test1\\test2",
"type":"folder",
"subfolders":[
]
},
{
"subfolders":[
{
"name":"C:\\xampp\\htdocs\\test\\test1\\test2\\test4",
"type":"folder",
"subfolders":[
]
},
{
"subfolders":null
}
]
},
{
"name":"C:\\xampp\\htdocs\\test\\test1\\test3.txt",
"type":"file"
}
]
},
{
"name":"C:\\xampp\\htdocs\\test\\test_1.php",
"type":"file"
}
]
结果应该是这样的:
[
{
"folder1": {
"name": "test1.txt",
"type": "file",
"subfolders": {
"subfolder1": {
"name": "test1",
"type": "folder"
},
"subfolder2": {
"name": "test2",
"type": "folder",
"subfolders": {
"subfolder3": {
"name": "test3",
"type": "folder"
},
"subfile":{
"name":"test3.txt"
"type":"file"
}
}
}
}
}
}
]
我希望我能解释一下我的情况。结果,datas不在一个back datas中。
【问题讨论】:
-
“我的文件夹树类型应如下所示” - 您的预期结果是无效的 JSON。请给我们一个有效的例子。
-
@MagnusEriksson 我试图解释更多,我无法完全按照我的意愿制作 json 格式。
-
@MagnusEriksson 我再次编辑了帖子,我最终可以添加 json 类型。
标签: php recursion tree treeview