Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to populate a directory structure in an array

I am developing an admin panel that shows the directory structure of a specific location on server. I have got a recursive php function that iterates through every file and folder there is. What I can't figure out is how can I store this directory structure in a php associative array like this:

array[foldername1][0]=file; // if the foldername1 contains a file
array[foldername1][foldername2][0]=file //if foldername1 contains another folder(foldername2) along with the file.

The rule i am trying to follow is; a folder should always be a key and file should always be at an index like this:

array[folder1][folder2][0]=file1;
array[folder1][folder2][1]=file2;

The function to populate this associative array should be generic as we never know what the directory structure can be. I want to json_encode this array back to my client and deal with it in javascript which is not a problem at the moment.

If this is a bad approach please let me know cauze there might be a better way to do this. I thought of using a flat array but i guess its a bad design.

like image 590
samach Avatar asked Dec 17 '22 06:12

samach


1 Answers

$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__), RecursiveIteratorIterator::CHILD_FIRST);
$r = array();
foreach ($ritit as $splFileInfo) {
   $path = $splFileInfo->isDir()
         ? array($splFileInfo->getFilename() => array())
         : array($splFileInfo->getFilename());

   for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
       $path = array($ritit->getSubIterator($depth)->current()->getFilename() => $path);
   }
   $r = array_merge_recursive($r, $path);
}

print_r($r);
like image 89
goat Avatar answered Dec 25 '22 22:12

goat