Question

I have small function which gives me Directory Folders/Files list as multidimensional Array.

How can I have directory list with following structure. (Schema no : 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;
}

My current folder list as array

$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 folder list as array

$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 => '...'
);
Was it helpful?

Solution

Try

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

OTHER TIPS

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

here is what you are looking for

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top