views:

54

answers:

3

I wrote a recursive function, which returns an array with the paths to all files/folders in a given path. An array is already sorted and returns the exact information i want, but i struggle to display it properly in html lists.

Array_of_paths = ( 
[0] => /path/to/folderA/
[1] => /path/to/folderA/subfolderAA/
[2] => /path/to/folderB/
[3] => /path/to/folderB/subfolderBB/
[4] => /path/to/folderB/subfolderBB/fileBB.txt
[5] => /path/to/folderB/fileB.txt
[6] => /path/to/folderC/
...
)

I want to put these paths in <ul>,<li> tags to see something like this:

   <ul>
     <li>/path/to/folderA/
         <ul>
           <li>/path/to/folderA/folderAA/</li>
         </ul>
     </li>
     <li>/path/to/folderB
         <ul>
           <li>/path/to/folderB/subfolderBB/
             <ul>
               <li>/path/to/folderB/subfolderBB/fileBB.txt</li>
             </ul>
           </li>
           <li>/path/to/folderB/fileB.txt</li>
         </ul>
     </li>
     <li>/path/to/folderC/</li>
   </ul>

=>

  • /path/to/folderA/
    • /path/to/folderA/folderAA/
  • /path/to/folderB
    • /path/to/folderB/subfolderBB/
      • /path/to/folderB/subfolderBB/fileBB.txt
    • /path/to/folderB/fileB.txt
  • /path/to/folderC/

I managed to find a couple of similars questions, but the answers were in Ruby language. So, what's the problem solving idea behind this?

+1  A: 
Byron Whitlock
A: 

IMHO it's better to store the data in a more efficient and more similar format, something hierarchical. You can explode() your array by / and create the tree via arrays, then it'll be easy to foreach the array and build the HTML list.

foreach ( $paths as $path )
{
    $pieces = explode('/', $path);
    foreach ( $pieces as $piece )
    {
        $pathtree[$piece] = '';
    }
}

This new $pathtree array is much smaller, probably 1/4th as small as your $paths array. From this point you just need to foreach it to build your HTML list tree.

TravisO
A: 

If your are in PHP5, use RecursiveDirectoryIterator and RecursiveIteratorIterator to do the job.

$dir = new RecursiveDirectoryIterator("/path");
$it  = new RecursiveIteratorIterator($dir);

foreach ($it as $key => $value) {
    // Use $it->getDepth() and $value->getRealpath() 
    // with Byron's code to generate your list
}
mexique1