用PHP增加数字(第一个没有数字)


Increase number with PHP (the first one is without a number)

我有一张幻灯片,它使用了标题(NivoSlider)。所以我用这个代码

<img src="<?php the_sub_field('sub_field_1'); ?>" alt="" title="#htmlcaption" />

我需要的很简单,但我真的不知道怎么做:

第一个图像将是#htmlcaption
第二个图像将是#htmlcaption1
第三个图像将是#htmlcaption2

我如何使用PHP来实现这一点?

关于:

for ($i=0; $i < ...; $i++) {
    echo '#htmlcaption' . ($i == 0 ? '' : $i) . "'n";
}

基本上,您要做的是迭代所需的元素总数,然后简单地将实际计数器插入元素的文本中:

<?php
$total_count = 3;
for ( $i = 0; $i < total_count; $i++ ){ 
  $additinal_parameter = ( $i > 0 )? $i : '';
  echo '<img ... title="#htmlcaption'. $additinal_parameter .'" />'
}
?>

请注意,如果迭代器($i)大于零,则需要进行额外的检查,因为我们不希望附加零。

这将输出如下内容:

<img ... title="#htmlcaption" />
<img ... title="#htmlcaption1" />
<img ... title="#htmlcaption2" />

使用以下内容会有什么想法?

<img src="<?php the_sub_field('sub_field_1'); ?>" alt="" title="#htmlcaption<?php echo $htmlcaption_i++; ?>" />

$htmlcaption_i++表示将打印该值,然后递增。第一次打印输出为'',第二次为'1',依此类推

建议在页面的开头设置$htmlcaption_i

<?php $htmlcaption_i = 0; ?>