图片文件夹有3个文件
<img src='images/AAA_1.jpg'>
<img src='images/AAA_2.jpg'>
<img src='images/AAA_3.jpg'>
<img src='images/BBB_1.jpg'>
<img src='images/BBB_2.jpg'>
<img src='images/BBB_3.jpg'>
<img src='images/CCC_3.jpg'>
PHP
foreach ($carousel as $image) {
if(strpos($image, 'AAA_') === 0){
echo "<div class='box'><img src='images/carousel/$image'/></div>";
}
}
所以输出是
<div class='box'>
<img src='images/AAA_1.jpg'>
</div>
<div class='box'>
<img src='images/AAA_2.jpg'>
</div>
<div class='box'>
<img src='images/AAA_3.jpg'>
</div>
如何在拳头框中添加first
课程,如
<div class='box first'>
<img src='images/AAA_1.jpg'>
</div>
<div class='box'>
<img src='images/AAA_2.jpg'>
</div>
<div class='box'>
<img src='images/AAA_3.jpg'>
</div>
答案 0 :(得分:1)
简单:使用旗帜。
$firstEchoed = FALSE;
foreach ($carousel as $image) {
if(strpos($image,'AAA_') === 0){
echo "<div class='box";
if ( ! $firstEchoed)
echo " first";
echo "'><img src='images/carousel/$image'/></div>";
$firstEchoed = TRUE;
}
}
答案 1 :(得分:1)
使用密钥:
foreach ($carousel as $key=>$image) {
$first = $key == 0 ? ' first' : '';
if(strpos($image,'AAA_') === 0){
echo <<<EOD
<div class='box{$first}'>
<img src='images/carousel/{$image}.jpg'>
</div>
EOD;
}
}
注意:我使用heredoc语句作为回声,因为我更喜欢在多行上回显多个HTML标记。
答案 2 :(得分:0)
您可以使用布尔标志,或将计数参数添加到 foreach :
foreach ($carousel as $i => $image)