douyinzha5820 2016-09-20 19:28
浏览 27
已采纳

如何在php中每隔3次迭代使用不同的内容

I'm trying to create a while statement that will give different results for the 4th and then every 3 after that for columns.

so its going to be iterations 1,4,7,10 etc

Here is what i have

$count = $query->post_count;
$i = 1;
$located="";

while ( $query->have_posts() ) : $query->the_post();

$located.= '<h2 class="gold"><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
$located.= $shopaddress.'</br>';
$located.= $opentime.' - '.$closetime.'</br>';
$located.= $shopphone.'</br>';
    if ($i == '1' || $i == '4'){ 
        $located.=".";  
    }else { 
        $located.=", ";
    }
$i++;

endwhile;

I was thinking that this would work

    if ($i - 1 % 3 == 0){ 
        $located.=".";  
    }else { 
        $located.=", ";
    }

but i'm it doesn't return results different results (presumably the math set wrong)

if ($i % 3 == 1) 

this seems to work but i'm not sure why and if it's just a fluke. how does this work?

  • 写回答

1条回答 默认 最新

  • douyuan4697 2016-09-20 19:31
    关注

    You were close...you just need to take into account order of operations and group your operators - it should be:

    if (($i - 1) % 3 == 0) 
    

    Your statement is executing the modulus first, so when $i = 4, you have (4 - (1 % 3)), which equals 3.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据