简体   繁体   中英

PHP want to loop through all the files in folders which folders are in folder

So basically I have folder which contains folders and in these folders i have

some images .jpg and some txt files

So i want to loop through these folders and then loop through all the files inside and append them to div via Javascript

So far ii will try something like this Just need some PHP advices and basically is this a proper way to do this

<?php
    $directory = '/path/to/files';

    if (! is_dir($directory)) {
        exit('Invalid diretory path');
    }    

    foreach (scandir($directory) as $file // $file needs to be replaced with $folder for examle) {
        if ('.' === $file) continue; //what is this doing
        if ('..' === $file) continue; // and what is this doing

         //get path of the current folder via PHP
         // create the div with classes and id via javascript 
         // i know javascript so i skip this part

        foreach (scandir($directory) as $file) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        //append img with src='php given path' and some classes
        //append some 'html h3' and some 'html p' and one 'html button'
        }
        //append the div with the html tags to a particular div i want
        // all  explained in '//' i can do via javascript so i need only help with PHP
    }


?>

I think in the firs loop i have to remove

if ('.' === $file) continue; 
 if ('..' === $file) continue;

If the structure is that simple as you describe then have a look at glob

if (! is_dir($directory)) {
    exit('Invalid diretory path');
}    

foreach (glob($directory . '/*', GLOB_ONLYDIR) as $folder) {

     echo $folder . PHP_EOL; // this is a debug output. You do not need it

     // full path to folder is in $folder
     //get path of the current folder via PHP
     // create the div with classes and id via javascript 
     // i know javascript so i skip this part

    foreach (glob($folder . '/*.{jpg,txt}',GLOB_BRACE) as $file) {

        echo $file . PHP_EOL; // this is a debug output. You do not need it

        // Full path to image is in $file
        //append img with src='php given path' and some classes
        //append some 'html h3' and some 'html p' and one 'html button'
    }
    //append the div with the html tags to a particular div i want
    // all  explained in '//' i can do via javascript so i need only help with PHP
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM