Проблема с подпапкой Scandir, перебор папок и файлов в отдельные массивы

building a site for a client who wants to be able to just upload files to their server (with specific naming) and have them parsed for the site content. I got it working great for the first initial folder but I am having a hard time exporting the subfolder files are their own array. Here is the code:

    $files = scandir(getcwd());
    foreach ($files as $file) {
        if(is_file($file)) {
            if ($file == 'description.txt') {
                // php less than or equal 5
                $description = file_get_contents('./description.txt', FILE_USE_INCLUDE_PATH);
            }
            if ($file == 'subtitle.txt') {
                // php less than or equal 5
                $subtitle = file_get_contents('./subtitle.txt', FILE_USE_INCLUDE_PATH);
            }
            if ($file == 'item.png') {
                $mainImage = 'item.png';
            }
            if ($file == 'item.jpg') {
                $mainImage = 'item.jpg';
            }
        } elseif (is_dir($file)) {
            $subFiles = scandir($file);
            foreach ($subFiles as $file2) {
                echo $file2;
            }
        }
    }
    

Проблема в том, что $file2 включает все файлы из родительского каталога, а не только элементы из подпапки. Если я повторю $files перед foreach, он также будет включать файлы подпапок и подпапок, что не является предпочтительным, но на самом деле не мешает тому, что я хочу сделать. Спасибо


person user24102    schedule 04.09.2014    source источник


Ответы (1)


Scandir также возвращает "." и «..», которые также являются каталогами, поэтому остальная часть вашего кода if(is_file($file)) { также выполняется. проверьте и пропустите "." и ".." во время цикла, который решит проблему

$files = scandir(getcwd());
foreach ($files as $file) {
    if(is_file($file)) {
        if ($file == 'description.txt') {
            // php less than or equal 5
            $description = file_get_contents('./description.txt', FILE_USE_INCLUDE_PATH);
        }
        if ($file == 'subtitle.txt') {
            // php less than or equal 5
            $subtitle = file_get_contents('./subtitle.txt', FILE_USE_INCLUDE_PATH);
        }
        if ($file == 'item.png') {
            $mainImage = 'item.png';
        }
        if ($file == 'item.jpg') {
            $mainImage = 'item.jpg';
        }
    } elseif (is_dir($file)) {
        if($file=="." || $file==".."){
            continue;
        }
        $subFiles = scandir($file);
        foreach ($subFiles as $file2) {
            echo $file2;
        }
    }
}
person Sunand    schedule 04.09.2014