Using glob() to display images from a directory while echo'ing a unique first image

不打扰是莪最后的温柔 提交于 2019-12-11 03:42:07

问题


I am quite new to PHP and I did not want to ask anything here until I absolutely could not find a way to do this.

I have a situation where I would like to use PHP to read and display images from a directory but I would like the first image read to be echo'd uniquely

My current code as follows:

$imageDir = "img/landMarks/carousel/";
$images = glob($imageDir.'*.jpg');
foreach ($images as $image){
echo '<div class="item">'."\r\n\t\t";
echo '<img src="'.$image.'" alt=""></div>'."\r\n\t";}

Just a simple directory pull and echo with formatting.

This will be for a BootStrap carousel and unfortunately the first image in line has to have <div class="item active"> or the whole thing fails.

So to reiterate, the first image pulled needs to be <div class="item active"> while the rest need to be <div class="item">

I think I went through an entire pack of cigarettes wracking my brain around this.


回答1:


use a flag for that. hope to help.(-:

$imageDir = "img/landMarks/carousel/";
$images = glob($imageDir.'*.jpg');
$flag=1;
foreach ($images as $image){
echo '<div class="item' .($flag?' active':''). '">'.PHP_EOL."\t\t";
echo '<img src="'.$image.'" alt=""></div>'.PHP_EOL."\t";
$flag=0;
}



回答2:


How about using a for loop instead of a foreach loop. When index == 0 you can add "active" to your div's class.

Note I didn't run this code- but it should give you the right idea.

$imageDir = "img/landMarks/carousel/";
$images = glob($imageDir.'*.jpg');
for($i = 0; $i < count($images); $i++){
       //If the index is 0, it's the first image.
       $class = ($i == 0) ? 'item active' : 'item';

       //Dynamically change your div's class
       echo "<div class='$class'>\r\n\t\t";
       echo '<img src="'.$images[$i].'" alt=""></div>'."\r\n\t";
}


来源:https://stackoverflow.com/questions/16613630/using-glob-to-display-images-from-a-directory-while-echoing-a-unique-first-im

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!