PHP 总是显示 3 个 li 元素,即使 while 循环测试表达式为假


PHP always show 3 li elements even if while loop test expression is false

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

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

法典

<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>';

我知道一段时间循环可能不是最好的解决方案,但是,我不确定如何处理不同的解决方案。

编辑

<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>
<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>

无论调用 has_sub_field 的结果如何,for 循环都将执行 3 次。 看起来 - 基于您在初始测试中获得的结果 - 一旦has_sub_field返回false,下一次对has_sub_field的调用将重置其内部索引,并将从头开始。

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

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

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