【问题标题】:PHP always show 3 li elements even if while loop test expression is falsePHP 总是显示 3 个 li 元素,即使 while 循环测试表达式为假
【发布时间】:2014-08-15 13:53:48
【问题描述】:

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

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

代码

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

【问题讨论】:

    标签: php html loops layout


    【解决方案1】:
    <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 设置为true 第一次has_sub_field 返回false 然后使用$done 来决定何时打印子字段以及何时打印占位符&lt;li&gt;

    【讨论】:

    • 这在有 1 个艺术家的情况下有效,然后它在位置 3 重复艺术家 1?那么,艺术家 1 - 占位符 - 艺术家 1??
    • 我用for循环看了一下,搞不明白,菜鸟错误
    • 很好...你解决得太快了 :) 谢谢你的帮助
    • 很好的解释
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2012-10-26
      • 2019-04-07
      • 2017-09-18
      • 2014-03-30
      相关资源
      最近更新 更多