尝试为每个必须从0开始的图像获得越来越多的数字,它当前从1输出,我不知道为什么!
感谢任何帮助,提前谢谢!
<div id="carousel">
<ul class="thumbs">
<?php $counts = 0 ; ?>
<?php foreach( $images as $image ): $counts++; ?>
<li>
<a data-slide-index="<?php echo $counts ;?>" href="">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
答案 0 :(得分:1)
foreach( $images as $image ): $counts++;
在第一次迭代时运行。因此
$counts = 0;
foreach( $images as $image ): $counts++;
$counts == 1 // true on first iteteration
你可以做
$counts = -1 // Code smell!
或
<?php
$counts = 0 ;
foreach( $images as $i => $image )?>
<li>
<a data-slide-index="<?php echo $i ?>" href="#">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
</li>
<?php endforeach; ?>
答案 1 :(得分:1)
在使用之前增加$counts
。你从0开始,但是一旦你启动foreach并运行$counts++;
它就会变为1。
将$counts++;
移动到foreach循环的末尾。
<?php $counts = 0 ; ?>
<?php foreach( $images as $image ) : ?>
<li>
<a data-slide-index="<?php echo $counts; ?>" href="">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
</a>
</li>
<?php $counts++; ?>
<?php endforeach; ?>
答案 2 :(得分:0)
因为您在$counts
echo
所以就这样做:
<?php $counts = -1 ; ?>
或者这个:
foreach( $images as $image )
{
echo '<li>
<a data-slide-index="' . $counts . '" href="">
<img src="' . $image['sizes']['thumbnail'] . '" alt="' . $image['alt'] . '" /></a>
</li>';
$counts++;
}
答案 3 :(得分:0)
而不是
<?php foreach( $images as $image ): $counts++; ?>
做
<?php $counts++; endforeach; ?>
在文本打印后增加。
答案 4 :(得分:0)
编写如下代码:
<div id="carousel">
<ul class="thumbs">
<?php $counts = 0 ; ?>
<?php foreach( $images as $image ) { ?>
<li>
<a data-slide-index="<?php echo $counts ;?>" href="">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
</li>
<?php $counts++; } ?>
</ul>
</div>
<?php endif; ?>
答案 5 :(得分:0)
尝试此代码
<div id="carousel">
<ul class="thumbs">
<?php $counts = 0 ; ?>
<?php foreach( $images as $image ): $counts++; ?>
<li>
<a data-slide-index="<?php if($counts == 1){echo '0';}else {echo $counts
;} ?>" href="">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>