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.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效