在PHP循环中使用计数器

时间:2016-01-29 18:38:38

标签: php wordpress flexslider

我使用Flexslider插件一次显示三个产品的幻灯片。产品数量因页面而异。为了确保插件一次只显示三个,我使用的是一个简单的计数器:

<ul class="slides row">
<li>
    <?php
    $counter = 0;
    while ( have_rows('series_solutions') ) : the_row();
        $counter++;
    ?>
    <div class="col-md-4 series-detail">
        <?php $series_image = get_sub_field('solution_image');
          echo '<img class="img-responsive center-block" src="' . $series_image['url'] . '" alt="' . $series_image['alt'] . '" />';
        ?>
        <span class="series-number"><?php the_sub_field('solution_number');?></span>
        <span class="series-description"><?php the_sub_field('solution_description');?></span>

        <span class="series-screen"><?php the_sub_field('solution_screen_dimensions');?></span>
        <span class="series-body"><?php the_sub_field('solution_body_dimensions');?></span>
        <span class="series-resolution"><?php the_sub_field('solution_resolution');?></span>
        <span class="series-shop"> <a class="btn btn-primary" href="<?php the_sub_field('solution_spec_sheet_link');?>" target="_blank">Download the Spec Sheet</a>
        </span>
    </div><!-- col-md-4-->
    <?php 
    if ($counter % 3 == 0) {
        echo "</li><li>";
    }?>
    <?php endwhile;?>
</li></ul>

问题是,Flexslider会查找<li>个元素来确定幻灯片内容的开头和结尾。如果一个页面只有三个产品,那么该计数器仍会添加</li><li>,Flexslider将其解释为新的和空白幻灯片:

enter image description here

如果没有数据证明合理,那么该计数器的结构是否可以阻止生成开放<li>

1 个答案:

答案 0 :(得分:0)

我想这是一个众所周知的问题。这个解决方案怎么样(未经测试但应该是这样的):

  <ul class="slides row">
        <?php
        $counter = -1;
        while ( have_rows('series_solutions') ) : the_row();
            $counter++;

        if ($counter % 3 == 0) {
            echo "<li>";
        }?>
        <div class="col-md-4 series-detail">
            <?php $series_image = get_sub_field('solution_image');
              echo '<img class="img-responsive center-block" src="' . $series_image['url'] . '" alt="' . $series_image['alt'] . '" />';
            ?>
            <span class="series-number"><?php the_sub_field('solution_number');?></span>
            <span class="series-description"><?php the_sub_field('solution_description');?></span>

            <span class="series-screen"><?php the_sub_field('solution_screen_dimensions');?></span>
            <span class="series-body"><?php the_sub_field('solution_body_dimensions');?></span>
            <span class="series-resolution"><?php the_sub_field('solution_resolution');?></span>
            <span class="series-shop"> <a class="btn btn-primary" href="<?php the_sub_field('solution_spec_sheet_link');?>" target="_blank">Download the Spec Sheet</a>
            </span>
        </div><!-- col-md-4-->
        <?php 
        if ($counter % 3 == 2) {
            echo "</li>";
        endwhile;

if($counter % 3 != 2) {
    echo "</li>";
}

?>
    </ul>