PHP中深层递归的目录结构数组

Kdg*_*Dev 18 php arrays recursion

我正在尝试将硬盘上的一些文件夹放入阵列中.

例如,度假照片.假设我们有这样的结构:

  • 设置1
    • 第1组第1项
    • 第1组第2项
    • 第1组的项目
  • 设置2
    • 第2组的子集1
      • 第2组第1项的第1项
      • 第2组的子集1的项目....
    • 第2组的子集2
    • 随机文件,而不是目录.
  • 设置3
  • ...

我希望有这样的东西,作为一个数组.
意思是我有一个大数组,在该数组中有更多数组.每个集合和子集都有自己的数组.

我试图让它看起来像这样:

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(...)
    ...
)
Run Code Online (Sandbox Code Playgroud)

我偶然发现了这个问题:http://www.the-art-of-web.com/php/dirlist/

但这不是我想要的.我一直在干涉它,但它只给我带来麻烦.

这是一个示例,查看更大分辨率的源(没有明显点击...). 例

Pet*_*ley 41

我建议使用DirectoryIterator来构建您的数组

这是我快速拼凑的一个片段,但我目前没有测试它的环境,所以准备调试它.

$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;
}
Run Code Online (Sandbox Code Playgroud)


sou*_*rge 14

一个没有任何错误处理的简单实现:

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;
}
Run Code Online (Sandbox Code Playgroud)


tim*_*tim 6

根据@ soulmerge的答案代码.我刚刚删除了一些nits和注释,并将其$startpath用作我的起始目录.(谢谢@soulmerge!)

function dirToArray($dir) {
    $contents = array();
    foreach (scandir($dir) as $node) {
        if ($node == '.' || $node == '..') continue;
        if (is_dir($dir . '/' . $node)) {
            $contents[$node] = dirToArray($dir . '/' . $node);
        } else {
            $contents[] = $node;
        }
    }
    return $contents;
}

$r = dirToArray($startpath);
print_r($r);
Run Code Online (Sandbox Code Playgroud)