目录文件夹/文件列表到Array php

时间:2014-05-01 18:13:58

标签: php arrays recursion multidimensional-array iteration

我有一个小功能,它将目录文件夹/文件列表作为多维数组。

如何拥有具有以下结构的目录列表? (图式编号:3)

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

我当前的文件夹列表为数组

$files = array (
  0 => 'do-update.php',
  1 => 'sitemap.xml',
  2 => 'sitemap.xml.gz',
  3 => 'wp-config.php',
  'wp-content' => 
  array (
    'uploads' => 
    array (
      2013 => 
      array (
        '05' => 
        array (
          0 => 'kabeduvarkad-1024x768.jpg',
          1 => 'kabeduvarkad-150x150.jpg',
          2 => 'kabeduvarkad-300x225.jpg',
          3 => 'kabeduvarkad-940x198.jpg',
        ),
        10 => 
        array (
        ),
      ),
      2014 => 
      array (
        '02' => 
        array (
        ),
      ),
      2015 => 'de.php',
    ),
  ),
  'wp-update' => 
  array (
    0 => 'wp-update.tar',
    1 => 'wp-update.tar.gz',
    2 => 'wp-update1.tar',
    3 => 'wp-update1.tar.gz',
  ),
  4 => 'wp-update.tar.gz',
);

预期文件夹列表为数组

$expected = array (
  0 => 'do-update.php',
  1 => 'sitemap.xml',
  2 => 'sitemap.xml.gz',
  3 => 'test.php',
  4 => 'wp-config.php',
  5 => 'wp-content/',
  6 => 'wp-content/uploads/',
  7 => 'wp-content/uploads/2013/',
  8 => 'wp-content/uploads/2013/05/',
  9 => 'wp-content/uploads/2013/05/kabeduvarkad-1024x768.jpg',
  10 => 'wp-content/uploads/2013/05/kabeduvarkad-150x150.jpg',
  11 => 'wp-content/uploads/2013/05/kabeduvarkad-300x225.jpg',
  12 => 'wp-content/uploads/2013/05/kabeduvarkad-940x198.jpg',
  13 => 'wp-content/uploads/2013/05/kabeduvarkad.jpg',
  14 => '...'
);

2 个答案:

答案 0 :(得分:0)

$path = realpath('yourfolder/examplefolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) {
    echo "$filename\n";
}

这是你要找的东西

答案 1 :(得分:0)

尝试

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

     $dir='abcd'; $result=dirToArray($dir); 
     $it= new RecursiveIteratorIterator (new RecursiveArrayIterator($result));                                 $l=iterator_to_array($it,false); 
     echo '<pre>'; 
     print_r($l); 
     echo '</pre>';