Как-то так:
<?php
function tree($dirName) {
$tree = [];
$dir = opendir($dirName);
while (($entry = readdir($dir)) !== false) {
if ($entry === '.' || $entry === '..') {
continue;
}
$fullName = "{$dirName}\\{$entry}";
if (is_dir($fullName)) {
$tree[] = [
'name' => $entry,
'type' => 'dir',
'entries' => tree($fullName)
];
} else {
$tree[] = [
'name' => $entry,
'type' => 'file'
];
}
}
return $tree;
}
print(json_encode(tree('C:\\test'), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
/* [
{
"name": "dir1",
"type": "dir",
"entries": [
{
"name": "dir2",
"type": "dir",
"entries": [
{
"name": "file5",
"type": "file"
}
]
},
{
"name": "file1",
"type": "file"
},
{
"name": "file3",
"type": "file"
}
]
},
{
"name": "file2",
"type": "file"
}
] */