0

I'm using php to make a code that will basically scan a directory and list out folders and files and then the files in the subfolder, something like what you see in a gui... What I'm doing is manually doing the listing. This is a quite simple understandable code so I hope you all understand.

Even if I can get a generic coding answer, I'll implement it into this

<?php
$dir = '/Users/USERNAME/documents/images';
$files = scandir($dir);
function removedefault($arr){ //Removing macos default file names
    $newarr = \array_diff($arr, array('.', '..', '.DS_Store'));
    return $newarr;
}
$files = removedefault($files);
$mainarray = array();


foreach ($files as $name) {
    if (is_dir($name)) {
        $fstdir = removedefault(scandir($name));
        foreach ($fstdir as $fstdirname) {
            if (is_dir($name . '/' . $fstdirname)) {
                $snddir = removedefault(scandir($name . '/' . $fstdirname));
                foreach ($snddir as $snddirname) {
                    if (is_dir($name . '/' . $fstdirname . '/' . $snddirname)) {
                        $thrdir = removedefault(scandir($name . '/' . $fstdirname . '/' . $snddirname));
                        foreach ($thrdir as $thrdirname) {
                            if (is_dir($name . '/' . $fstdirname . '/' . $snddirname . '/' . $thrdirname)) {
                                pass;
                                //Format will continue here.....
                            }else{
                                $mainarray[$name][$fstdirname][$snddirname][] = $thrdirname;
                            }
                        }
                    }else{
                        $mainarray[$name][$fstdirname][] = $snddirname;     
                    }
                }

            }else{
                $mainarray[$name][] = $fstdirname;
            }
        }
    }else{
        $mainarray[] = $name;
    }
}
var_dump($mainarray);

As you can see, it gets repetitive, how do I make such a code continuous?

  • 2
    *recursion* is the word you are looking for (a function calling itself) – Cid Jan 13 '21 at 09:10
  • How can I use that? – CryptoRhino Jan 13 '21 at 09:11
  • 1
    _“How can I use that?”_ - when you are given a keyword you are hearing for the first time - then please do your own research first, instead of asking for a personal explanation right away. – CBroe Jan 13 '21 at 09:12
  • I know what a recursive function is, the only problem I'm facing with that is the directory changes everytime it enters a new directory to scan, I'm not able to make out in my mind how to write that recursive function which will be able to take the directory inside it – CryptoRhino Jan 13 '21 at 09:14

0 Answers0