Вопрос

I'm trying to loop through a folder and print the images within it in an html list. The output must be assigned to the $bgFinal variable.

It's managing to output all items within the folder, but it's also outputting two items that don't exist before it outputs the actual existing items.

$files = scandir('../admin/js/3rd_party/tctc91_custom/bg');
if ($files !== false) 
{
    $bgFinal = '<ul>';
    foreach($files as $f) { 
        $bgFinal .= '<li><img src="../admin/js/3rd_party/tctc91_custom/bg/'.$f.'" alt="'.$f.'" id="'.$f.'" /></li>';
    }
    $bgFinal .= '</ul>';
}

example of the output (the bg folder contains 4 images):

<ul>
    <li><img src="../admin/js/3rd_party/tctc91_custom/bg/." alt="." id="."></li>
    <li><img src="../admin/js/3rd_party/tctc91_custom/bg/.." alt=".." id=".."></li>
    <li><img src="../admin/js/3rd_party/tctc91_custom/bg/1.png" alt="1.png" id="1.png" style="opacity: 0.6; "></li>
    <li><img src="../admin/js/3rd_party/tctc91_custom/bg/2.png" alt="2.png" id="2.png"></li>
    <li><img src="../admin/js/3rd_party/tctc91_custom/bg/3.png" alt="3.png" id="3.png"></li>
    <li><img src="../admin/js/3rd_party/tctc91_custom/bg/4.png" alt="4.png" id="4.png" style="opacity: 0.6; "></li>
</ul>
Это было полезно?

Решение

Those dots stand for the current and parent directories. scandir takes those into account as well as your other items.

See the code that someone posted on php.net: to take the

array_diff(scandir($directory), array('..', '.'))

Другие советы

The directories . (dot) and .. (dot dot)

The filename . (dot) represents the current working directory; and the filename .. (dot dot) represent the directory one level above the current working directory, often referred to as the parent directory.

Try this code

$files = array_diff(scandir('../admin/js/3rd_party/tctc91_custom/bg'), array('..', '.'));
if ($files !== false) 
{
    $bgFinal = '<ul>';
    foreach($files as $f) { 
        $bgFinal .= '<li><img src="../admin/js/3rd_party/tctc91_custom/bg/'.$f.'" alt="'.$f.'" id="'.$f.'" /></li>';
    }
    $bgFinal .= '</ul>';
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top