How can I save a directory tree to an array in PHP?

Posted by Greg on Stack Overflow See other posts from Stack Overflow or by Greg
Published on 2010-12-21T05:27:40Z Indexed on 2010/12/21 5:31 UTC
Read the original article Hit count: 250

Filed under:
|
|
|

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;
}

© Stack Overflow or respective owner

Related posts about php

Related posts about file-upload