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