any help?
Jun 4, 2020
13
Level 1
List all the files and folders in a Directory with PHP recursive function
I'm trying to go through all of the files in a directory, and if there is a directory, go through all of its files and so on until there are no more directories to go to. I need to get like JSON below.
$routes = [
'/RootFolder/Folder1/File1.doc',
'/RootFolder/Folder1/SubFolder1/File1.txt',
'/RootFolder/Folder1/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc',
];
data: [{
label: 'RootFolder',
children: [{
label: 'Folder1',
children: [{
file: 'File1.doc'
}],
children: [{
label: 'SubFolder1',
children: [{
file: 'File1.txt'
}, {
file: 'File2.txt'
}],
}]
},
{
label: 'Folder2',
children: [{
label: 'SubFolder1',
children: [{
file: 'File1.txt'
}, {
file: 'File2.txt'
}, {
label: 'SubSubFolder1',
children: [{
file: 'File4.doc'
}, ],
}]
}]
},
],
}],
Level 33
Hi @xerk
My bad, I assumed the first level directory wouldn't change (since you named it in your example "RootFolder"):
Try this:
$routes = [
'/pictures/proof/Ek7rdD8ljxfkvnUDP4jj23kofsLKtmj9mfVVMZ42.jpg',
'/pictures/proof/hTIYjQyJdkTTtCKOtVfVbIUiEbZhOfQC3sH74txk.jpg',
'/projects/Motawer/2020/asd/Final Files/4IEibhzjUshSUN6Dkq21A7pRcAotOGsur0Touv59.png',
'/pictures/proof/p20xnbXq4nRAOk2bCJ2OvdBhYc08ghjvs7Vc98WQ.jpg',
'/projects/Motawer/2020/asd/Proofs/yr6icxnAIYz95eDXjy446yjVc8gKJ5b6mO1kvfqk.jpg',
'/projects/Motawer/2020/asd/yr6icxnAIYz95eDXjy446yjVc8gKJ5b6mO1kvfqk.jpg',
'/projects/Motawer/2020/asd/Proofs2/yr6icxnAIYz95eDXjy446yjVc8gKJ5b6mO1kvfqk.jpg',
'/sarasa.jpg',
];
function routesToArray($routes)
{
$routeList = [];
foreach ($routes as $route) {
if (substr_count($route, '/') > 1) {
$pathName = Str::after($route, '/');
$pathName = Str::beforeLast($pathName, '/');
$pathName = $pathName . '/!@_files';
} else {
$pathName = '!@_files';
}
$pathName = str_replace('/', '.', $pathName);
$fileName = Str::afterLast($route, '/');
$existingFiles = Arr::get($routeList, $pathName) ?? [];
$newFile = [
[
'file' => $fileName,
'url' => $route
]
];
$files = array_merge($existingFiles, $newFile);
Arr::set($routeList, $pathName, $files);
}
return $routeList;
}
function getTreeBranches($paths)
{
$tree = [];
foreach ($paths as $key => $path) {
if($key === '!@_files') {
$tree = array_merge($tree, $path);
continue;
}
$tree[] = [
'label' => strval($key),
'children' => getTreeBranches($path),
];
}
return $tree;
}
$routeList = routesToArray($routes);
$routeTree = [
'data' => getTreeBranches($routeList)
];
var_dump(json_encode($routeTree, JSON_PRETTY_PRINT));
I updated the script to allow files on the top level folder and files in the same level as directories that contain other files.
1 like
Please or to participate in this conversation.