0

I'm using the following code to get an array of directories and their sub-directories where each contain file type extension: png. It works great but I need to be able to output the results of the array in a list style format e.g.

* Test
  -> test2.png
  -> test1.png
  * subfolder
    -> test3.png
    * sub sub folder
      -> test4.png

etc

Code:

$filter=".png";  
$directory='../test';  
$it=new RecursiveDirectoryIterator("$directory");
foreach(new RecursiveIteratorIterator($it) as $file){  
    if(!((strpos(strtolower($file),$filter))===false)||empty($filter)){  
        $items[]=preg_replace("#\\\#", "/", $file);  
    }
}

Example array of results:

array (
  0 => '../test/test2.png',
  1 => '../test/subfolder/subsubfolder/test3.png',
  2 => '../test/subfolder/test3.png',
  3 => '../test/test1.png',
)

What would be the best way of achieving the desired result?

Jørgen R
  • 10,568
  • 7
  • 42
  • 59

2 Answers2

0

In your if-clause, try:

$items[]=preg_replace("#\\\#", "/", $file->getPathName());

This should give you an output close to the one you desire. However, getPathName outputs absolute paths.

Turbotoast
  • 141
  • 5
  • Thanks. But I'm after displaying it as formatted text on a website e.g. Directory-> - Image - Image - Directory -> - Image - Image So one can see a structural representation of the data. –  Mar 23 '10 at 13:37
  • Ah, okay. Misunderstood you there. – Turbotoast Mar 23 '10 at 13:50
0

If you want to display files before directories, then you can't do it simply in a loop, because you won't know if more files would come later.

You need to aggregate the data in a tree (array of arrays indexed by path component) or sort it.

$components = explode('/',$path);
$file = array_pop($components);
$current = $root;
foreach($components as $component) {
  if (!isset($current[$component])) $current[$component] = array();
  $current = &$current[$component];
}
$current[$file] = true;

It should give you structure such as:

array(
  'test'=>array(
      'test1.png'=>true,
      'subfolder'=>array(
      … 

That will be straightforward to work with (of course that kinda defeats the purpose of RecursiveDirectoryIterator. You could get the same by recursively using regular DirectoryIterator).

Or if you sort paths by depth (write your comparison function), then you'll be able to output it simply by printing last path component with appropriate indentation.

Kornel
  • 97,764
  • 37
  • 219
  • 309