Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep recursive array of directory structure in PHP

I'm trying to put some folders on my hard-drive into an array.

For instance, vacation pictures. Let's say we have this structure:

  • Set 1
    • Item 1 of Set 1
    • Item 2 of Set 1
    • Item ... of Set 1
  • Set 2
    • Subset 1 of Set 2
      • Item 1 of Subset 1 of Set 2
      • Item ... of Subset 1 of Set 2
    • Subset 2 of Set 2
    • Random file, not a dir.
  • Set 3
  • ...

I want to have something like that, as an array.
Meaning I have 1 big array and in that array are more arrays. Each set and subset gets its own array.

I'm trying to make it look something like this:

Array
(
    [Set 1] => Array([0] => Item 1 of Set 1, [1] => Item 1 of Set 1,...)
    [Set 2] => Array([Subnet 1] => Array([0] => Item 1 of Subset 1 of Set 2,[1] => ...), [Subnet 2] => Array([0] => ..., ..., ...), ..., [0] => Random File)
    [set 3] => Array(...)
    ...
)

I came across this: http://www.the-art-of-web.com/php/dirlist/

But that's not what I'm looking for. I've been meddling with it but it's giving me nothing but trouble.

Here's an example, view source for larger resolution(no clicking apparently...). Example

like image 483
KdgDev Avatar asked Jun 04 '09 18:06

KdgDev


2 Answers

I recommend using DirectoryIterator to build your array

Here's a snippet I threw together real quick, but I don't have an environment to test it in currently so be prepared to debug it.

$fileData = fillArrayWithFileNodes( new DirectoryIterator( '/path/to/root/' ) );

function fillArrayWithFileNodes( DirectoryIterator $dir )
{
  $data = array();
  foreach ( $dir as $node )
  {
    if ( $node->isDir() && !$node->isDot() )
    {
      $data[$node->getFilename()] = fillArrayWithFileNodes( new DirectoryIterator( $node->getPathname() ) );
    }
    else if ( $node->isFile() )
    {
      $data[] = $node->getFilename();
    }
  }
  return $data;
}
like image 57
Peter Bailey Avatar answered Sep 19 '22 14:09

Peter Bailey


A simple implementation without any error handling:

function dirToArray($dir) {
    $contents = array();
    # Foreach node in $dir
    foreach (scandir($dir) as $node) {
        # Skip link to current and parent folder
        if ($node == '.')  continue;
        if ($node == '..') continue;
        # Check if it's a node or a folder
        if (is_dir($dir . DIRECTORY_SEPARATOR . $node)) {
            # Add directory recursively, be sure to pass a valid path
            # to the function, not just the folder's name
            $contents[$node] = dirToArray($dir . DIRECTORY_SEPARATOR . $node);
        } else {
            # Add node, the keys will be updated automatically
            $contents[] = $node;
        }
    }
    # done
    return $contents;
}
like image 25
soulmerge Avatar answered Sep 19 '22 14:09

soulmerge