PHP 循环:在每三个项目语法周围添加一个 div [英] PHP loop: Add a div around every three items syntax

查看:29
本文介绍了PHP 循环:在每三个项目语法周围添加一个 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$i = 1;if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();//如果是第一篇文章,第三篇文章等等.if("$i 是 3-1 的倍数") {echo '

';}//发布内容...//如果是第 3 个帖子,第 6 个帖子等if("$i 是 3 的倍数") {echo '</div>';}$i++;终了;万一;

我该如何实现?谢谢!

解决方案

为什么不执行以下操作?这将在第三个帖子后打开并关闭它.然后在没有显示 3 的倍数的情况下关闭结束的 div.

$i = 1;//之前添加以确保它被打开echo '

';if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();//发布内容...//如果 3 的倍数关闭 div 并打开一个新的 divif($i % 3 == 0) {echo '</div><div>';}$i++;终了;万一;//确保打开的div是关闭的回声'</div>';

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

I'm using a loop in wordpress to output posts. I want to wrap every three posts inside of a div. I want to use a counter to increment on each iteration of the loop but I'm not sure of the syntax that says "if $i is a multiple of 3" or "if $i is a multiple of 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;

How do I make this happen? thanks!

解决方案

Why not do the following? This will open it and close it after the third post. Then close the ending div in the event there is not a multiple of 3 to display.

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

In case you didn't know, % is the modus operator will return the remainder after the two numbers are divided.

这篇关于PHP 循环:在每三个项目语法周围添加一个 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆