PHP 想要遍历文件夹中文件夹中的所有文件


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

所以基本上我有包含文件夹的文件夹,在这些文件夹中我有

一些图像.jpg和一些 TXT 文件

所以我想遍历这些文件夹,然后遍历里面的所有文件,并通过 Javascript 将它们附加到div

到目前为止,我会尝试这样的事情只需要一些PHP建议,基本上这是一种正确的方法吗

<?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
    }

?>

我认为在冷杉循环中我必须删除

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

如果结构像你描述的那样简单,那么看看 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
}