-1

is there a way to output a folder and its files like this using php

this is my directories

folder/12345/file1.php

folder/46745/file1.php

folder/57756/file1.php

i tried this ...

$a = glob("folder/*");

foreach ($a as $key) {

    echo $key."<br>";

}

but the output will be like this

folder/12345

folder/46745

folder/57756

i am trying to make output to be more like ...

folder/12345

file.php

folder/46745

file1.php

folder/57756

file.php

my point is how many file is inside a folder should be outputted below the folder. hope some one help me with this. thanks

  • Does this answer your question? [How to recursively iterate through files in PHP?](https://stackoverflow.com/questions/25909820/how-to-recursively-iterate-through-files-in-php) – nice_dev Jul 09 '20 at 05:48

2 Answers2

0

You want scandir: https://www.php.net/manual/en/function.scandir.php

scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] ) : array

Returns an array of filenames on success, or FALSE on failure.

Example:

$dirArr = ['folder/12345', 'folder/46745', 'folder/57756'];

foreach($dirArr as $dir){
    $fileArr = scandir($dir);
    echo $dir.'\r\n';
    print_r($fileArr);
    echo '\r\n';
}

Result:

folder/12345
file1.php
file2.php

folder/46745
file1.php

folder/57756
file1.php
file2.php
file3.php
symlink
  • 11,984
  • 7
  • 29
  • 50
  • hi, thanks for your time. have you tried this ? cause it is not working for me. it is outputted same as my own code. not as you showing in results as it should be. – student98735 Jul 09 '20 at 03:43
  • @student98735 Think you're looking for it to be recursive. See https://www.php.net/manual/en/function.scandir.php#110570 – user3783243 Jul 09 '20 at 04:01
  • @student98735 I don't have access to your files, but if you have files in a folder passed to `scandir()`, it will return an array of those file names. – symlink Jul 09 '20 at 04:06
0

Get the directories, loop them, get the files and their basename and implode on <br>:

foreach(glob("folder/*", GLOB_ONLYDIR) as $dir) {
    echo "$dir<br>";
    echo implode("<br>", array_map("basename", glob("$dir/*"))) . "<br>";
}

Or have a look at the RecursiveDirectoryIterator class.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87