views:

139

answers:

2

I am working on a file manager project and can't seem to get my head around doing a recursive directory listing where I only get the directories. Everything I've tried either leaves off empty sub-directories or won't work when I try to parse it into the return structure to my jQuery tree.

I've tried using an array, and the recursive iterators but nothing has work for me so far.

** Update **

Thanks to everyone's input I've whittled my code down to:

class image_management {

private $_user_id;
private $_user_name;
private $_user_path;    

/**
* Constructor
*/
function __construct($user_id, $user_name) {

  $this->_user_id = $user_id;
  $this->_user_name = $user_name;
  $this->_user_path = ORDER_ROOT.$this->_user_id;
}    

/**
* Cleanup the class and close connections
* 
*/
function __destruct() {
}

/**
* Get Image Folders
* Returns an HTML list of the folders under a users
* directory.
*  
* @param hash $user_id -user id hash
* @param string $user_name - users email address
* @return string - html list
*/
public function getHTMLTree() {

  $html = "<li><a href='#'>";
  $html .= $this->_user_name . "</a><ul>";

  $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->_user_path), RecursiveIteratorIterator::SELF_FIRST);
  foreach($objects as $file) {
    if($file->isDir() ) {
      $item = substr($file->getPathname(),strlen($this->_user_path));
      echo $item;
    }
  }
  return $html;
}

}

This gives me the output:

/home/printshi/public_html/test/orders/88a0a01afd3728af8f6710ed874267f3
/Aggie_Stuff
/Misc
/Misc/Christmas
/Misc/Christmas/santa
/Misc/Christmas/frosty
/Misc/test1
/Geek_Stuff

which is getting me closer, my issue now is that what I need to do is wrap all these elements in HTML so that I get an output like:

<ul>
<li>Aggie_Stuff</li>
<li>Misc<ul>
    <li>Christmas<ul>
        <li>santa</li>
        <li>frosty</li>
        </ul>
    </li>
    <li>test1</li>
    </ul>
<li>Geek_Stuff</li>

The recursion part I understand, it's just getting it to do the HTML that I can't seem to get my head around no matter how hard I try.

+1  A: 

Have a look at the DirectoryIterator class, especially the isDir function.

$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
        // recursion goes here.
    }
}
nickf
+1  A: 

RecursiveIteratorIterator and RecursiveDirectoryIterator can do this for you:

$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($iter as $file) {
    if ($file->getFilename() == '.') {
        echo $file->getPath() . PHP_EOL;
    }
}
Daniel Egeberg