【问题标题】:PHP loop: Add a div around every three items syntax [duplicate]PHP循环:围绕每三个项目语法添加一个div [重复]
【发布时间】:2012-02-15 09:36:26
【问题描述】:

我在 wordpress 中使用循环来输出帖子。我想将每三个帖子包装在一个 div 中。我想在循环的每次迭代中使用计数器递增,但我不确定“如果 $i 是 3 的倍数”或“如果 $i 是 3 - 1 的倍数”的语法。

$i = 1;
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // If is the first post, third post etc.
     if("$i is a multiple of 3-1") {echo '<div>';}

     // post stuff...

     // if is the 3rd post, 6th post etc
     if("$i is a multiple of 3") {echo '</div>';}

$i++; endwhile; endif;

我该如何做到这一点?谢谢!

【问题讨论】:

标签: php wordpress loops while-loop


【解决方案1】:

为什么不做以下事情?这将在第三个帖子后打开并关闭它。如果没有 3 的倍数可显示,则关闭结束 div。

$i = 1;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // post stuff...

     // if multiple of 3 close div and open a new div
     if($i % 3 == 0) {echo '</div><div>';}

$i++; endwhile; endif;
//make sure open div is closed
echo '</div>';

如果您不知道,% 是方式运算符将返回两个数字相除后的余数。

【讨论】:

  • 看起来不错——在速度或效率方面使用其中一种是否有优势?我认为使用模数运算符可以减少一行代码
  • 我现在明白了——如果没有 3 的倍数,使用模数将创建一个未闭合的 div。谢谢!
  • 我更喜欢这个,因为它确保关闭所有开口divs。我实际上要做的是获取第一个 div 并在循环外回显它。这样,即使只有 1 个,您也有一个打开/关闭标签。这将确保您不会破坏格式。它的实际处理根本不应该影响速度,因为它是一个“基本”方程。
  • 可能会帮助其他人删除空的第一个标签(或最后一个?)的东西正在将$i % 3 == 0 更改为$i !== 0 &amp;&amp; $i % 3 == 0 这完全相同,但确保我们不检查第一个 id。
  • 您还应该检查$wp_query-&gt;post_count 的长度,因为如果它等于$i$i % 3 == 0,那么您就不想输出&lt;/div&gt;&lt;div&gt;,因为它最后会是一个空的div你的html。仅供参考。
【解决方案2】:

使用modulus 运算符:

if ( $i % 3 == 0 )

在您的代码中,您可以使用:

if($i % 3 == 2) {echo '<div>';}

if($i % 3 == 0) {echo '</div>';}

【讨论】:

  • 你能帮我把它放在我在上面的答案中粘贴的代码的上下文中吗?
  • @j-man86:你可以使用它,将"$i is a multiple of 3-1"替换为$i % 3 == 0
【解决方案3】:
$i = 1;
$post_count=$wp_query->found_posts;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // post stuff...

     // if multiple of 3 close div and open a new div
     if($i % 3 == 0 && $i != $post_count) {echo '</div><div>';} elseif($i % 3 == 0 && $i == $post_count){echo '</div>';}

$i++; endwhile; endif;

【讨论】:

  • 如果你能包含一些关于你的代码的解释会更好。
  • 上面选择的答案是添加一个额外的div,我给出了解决方案,我粘贴的代码没有添加任何额外的div
  • 我想将此代码添加为评论,但我的声誉低于 50。
【解决方案4】:

如果你不需要额外的 div,你可以使用这个:

 $i = 0;

 $post_count = $wp_query->found_posts;

 if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) :$wp_query->the_post();

 // If is the first post, third post etc.
 ( ($i%3) == 0 ) ? echo '<div>' : echo '';

 // post stuff...

 // if is the 3rd post, 6th post etc or after the last element

( $i == ($post_count - 1) || (++$i%3) == 0 )  ? echo '</div>' : 
echo '';

endwhile; endif;

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多