Such a problem: you need to implement a tree of files and folders on the site. Accordingly, the attached files should be displayed under their parent folder, and files without a folder (located in the root directory) are simply displayed at the bottom of all the others. I have the following code:

function tmlFile($dir){ $ok = scandir($dir, 0); foreach($ok as $k=>$v){ if($v != '.' && $v != '..'){ if(is_dir($dir.$v) == true){ echo 'папка - > <b>'.$dir.$v.'</b><br>'; tmlFile($dir.$v.'/'); } elseif(is_file($dir.$v) == true){ echo 'файл -> '.$dir.$v.'<br>'; } } } } tmlFile($_SERVER['DOCUMENT_ROOT'].'/tpl/templates/default/'); 

Displays almost everything correctly, at least displays all folders and all files, but what is the error, you will understand from the picture:

alt text

As you can see, everything is in a heap. Red is highlighted, respectively, the folder and the files in it. What is not selected is simply the files in the directory (.tpl files). How to clean up?

  • Print the directory paths right away, and put the files into an array that you output after - Gedweb
  • @Gedweb, what about the files in the folder? They will not be displayed if you remove elseif - xenon

1 answer 1

As one of the possible solutions, the additional parameter $indent will be tmlFile() to the recursive function tmlFile() . At each iteration, you should increase the indent, so you can build the correct tree.

 <?php function tmlFile($dir, $indent = ''){ $ok = scandir($dir, 0); $indent .= '&nbsp;&nbsp;&nbsp;'; foreach($ok as $k=>$v){ if($v != '.' && $v != '..'){ if(is_dir($dir.$v) == true){ echo $indent.'папка - > <b>'.$dir.$v.'</b><br>'; tmlFile($dir.$v.'/', $indent); } elseif(is_file($dir.$v) == true){ echo $indent.'файл -> '.$dir.$v.'<br>'; } } } } tmlFile($_SERVER['DOCUMENT_ROOT'].'/tpl/templates/default/');