开发者

Display `pretty output` of directory content from array

开发者 https://www.devze.com 2022-12-24 14:17 出处:网络
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 开发者_如何学Pythonbe able to output th

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 开发者_如何学Pythonbe 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号