Deep recursive array of directory structure in PHP

后端 未结 5 2258
有刺的猬
有刺的猬 2020-11-27 18:22

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
    • Ite
5条回答
  •  一生所求
    2020-11-27 19:18

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

提交回复
热议问题