How can I save a directory tree to an array in PHP?
- by Greg
I'm trying to take a directory with the structure:
top
folder1
file1
folder2
file1
file2
And save it into an array like:
array
(
'folder1' => array('file1'),
'folder2' => array('file1', 'file2')
)
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:
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->isDir())
{
if (!in_array($relativePath, $output))
$output[$relativePath] = array();
}
}
return $output;
}