title: How can I save a directory tree to an array in PHP?
body: <p>I'm trying to take a directory with the structure:</p>
  
  <pre><code>top
      folder1
          file1
      folder2
          file1
          file2
  </code></pre>
  
  <p>And save it into an array like:</p>
  
  <pre><code>array
  (
      'folder1' =&gt; array('file1'),
      'folder2' =&gt; array('file1', 'file2')
  )
  </code></pre>
  
  <p>This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:</p>
  
  <pre><code>private function get_tree()
  {
      $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
      $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
      $output   = array();
  
      foreach($iterator as $file)
      {
          $relativePath = str_replace($uploads . DS, '', $file);
  
          if ($file-&gt;isDir())
          {
              if (!in_array($relativePath, $output))
                  $output[$relativePath] = array();
          }
      }
  
      return $output;
  }
  </code></pre>