<?php
$directoryTree = [
'accounting' => [
'documents' => [
],
'losses' => [
],
'profit' => [
]
],
'legal' => [
'documents' => [
]
]
];
$fileList = [
[
'name' => 'Overview.doc',
'dir_path' => []
],
[
'name' => 'Incorporation.doc',
'dir_path' => []
],
[
'name' => 'Profit And Loss.xls',
'dir_path' => ['accounting']
],
[
'name' => 'Profit 1.xls',
'dir_path' => ['accounting', 'profit']
],
[
'name' => 'Loss 1.xls',
'dir_path' => ['accounting', 'losses']
],
[
'name' => 'TOS Draft.doc',
'dir_path' => ['legal', 'documents']
],
[
'name' => 'Accounting Doc.pdf',
'dir_path' => ['accounting', 'documents']
],
];
function addFiles2DirectoryTree(array $files, array $directoryTree){
foreach($files as $file)
assignFileToPath($file["name"], $file["dir_path"], $directoryTree);
return $directoryTree;
}
function assignFileToPath($filename, $path, &$directoryTree){
while($key = array_shift($path))
$directoryTree = &$directoryTree[$key];
$directoryTree[] = $filename;
}
$finalOutput = addFiles2DirectoryTree($fileList, $directoryTree);
print_r($finalOutput);
preferences:
30.6 ms | 402 KiB | 5 Q