即使while循环测试表达式为false,PHP也始终显示3个li元素

时间:2014-08-15 13:53:48

标签: php html loops layout

我正在寻找一个很好的解决方案来始终显示一定数量的元素 - 在本例中为3 - 即使while循环测试表达式为false。

这是为了获得统一的网格布局,这样我就不需要使用相同高度的列等等......

CODE

<ul class="event__lineup">
    <?php 

    $l = 0;

    while ( has_sub_field('event_lineup') ) :

        echo '<li class="title" itemprop="performer" itemscope="" itemtype="http://schema.org/Person"><span itemprop="name">' . get_sub_field('event_artist') . '</span></li>';

        if ( $l == 2 ) : break; endif;

    $l++;

    endwhile;

    ?>
</ul>

我想使用占位符,如果说只有1位艺术家或2位:

echo '<li class="title">&nbsp</li>';

我理解while循环可能不是最佳解决方案,但是,我不确定如何处理不同的解决方案。

修改

<ul class="event__lineup">
    <?php

    for ($i = 0; $i < 3; $i++) {
        if ( has_sub_field('event_lineup') ) {
            echo '<li class="title" itemprop="performer" itemscope="" itemtype="http://schema.org/Person"><span itemprop="name">' . get_sub_field('event_artist') . '</span></li>';
        } else {
            echo '<li class="title">&nbsp</li>';
        }
    }

    ?>
</ul>

2 个答案:

答案 0 :(得分:3)

<ul class="event__lineup">
<?php

$done = false;

for ($i = 0; $i < 3; $i++) {
    if (!has_sub_field('event_lineup')) {
        $done = true;
    }

    if ($done) {
        echo '<li class="title">&nbsp</li>';
    } else {
        echo '<li class="title" itemprop="performer" itemscope="" itemtype="http://schema.org/Person"><span itemprop="name">' . get_sub_field('event_artist') . '</span></li>';
    }
}

?>
</ul>

for循环将执行3次,无论调用has_sub_field的结果如何。看来 - 根据您在初始测试中得到的结果 - 一旦has_sub_field返回false,下次调用has_sub_field将重置其内部索引,它将从开始。

因此,我们在$done第一次返回true时将has_sub_field设置为false,然后使用$done来决定何时打印子字段以及何时我们打印占位符<li>

答案 1 :(得分:0)

在循环之后放置此元素应该检查缺少多少元素以达到显示和回显正确数量的占位符的最小数量:

$minimumNumberToShow = 3;
if($l < 3){
  for($i; $ < ($minimumNumberToShow-$l);; $i++){
    echo '<li class="title">&nbsp</li>';
  }
}