I am trying to build a file tree array with PHP based on the data blueprint from var treeData from Tree View - Vue.js (visible in javascript tab).
var treeData = [
{
name: 'My Tree',
children: [
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [
{
name: 'child folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
},
{ name: 'hello' },
{ name: 'wat' },
{
name: 'child folder',
children: [
{ name: 'hello' },
{ name: 'wat' }
]
}
]
}
]
},
{name: 'My tree 2'}
]
I was able to build a tree array with the following answer: PHP - create dynamic multidimensional file tree array.
But the format seen in the Vue.js docs is more suitable for that case. I did not find a way to build the array without defining the directories as keys.
$fileTree = dir_tree('/xy');
return $fileTree;
function dir_tree($dir) {
$files = array_map('basename', glob("$dir/*"));
foreach($files as $file) {
if(is_dir("$dir/$file")) {
$return[$file] = dir_tree("$dir/$file");
} else {
$return[] = [
'name' => $file,
'type' => explode('.', $file)[1]
];
}
}
return $return;
}
Which currently results to the following array:
{
"folder1": {
"0": {
"name": "test1.txt",
"type": "txt"
},
"child folder1": [
{
"name": "sample.png",
"type": "png"
}
]
},
"folder2": [
{
"name": "test2.txt",
"type": "txt"
}
]
}
Is there a way to manage that?