download1002 2014-04-03 15:35
浏览 63
已采纳

在打印2行后,php foreach甚至奇数反之亦然

In my application I have to loop images with two sizes. Lets call them large and small.. These images are in two columns like below.

large small
large small
large small

I produce the larage/small image by a class by doing this now like this:

<?php $count = 0; ?>
<?php foreach ($posts as $post) : ?>
<div class=" <?=(++$count%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">
<?php endforeach; ?>

What I would like to do here by now is to produce this list;

large small
small large
large small
etc..

In what kind of way can I do this? I guess I have to create a kind of reset after each 2 entries and set odd to eve and vise versa ?

  • 写回答

3条回答 默认 最新

  • doujue6196 2014-04-03 15:42
    关注

    In general if you need A B; B A; A B; etc in consecutive loops, you could do this:

    $row = 0;
    foreach ($posts as $post) {
      if ($row%2) echo "A, B
    "; else echo "B, A
    ";
      $row++;
    }
    

    This looks quite a bit like your code…

    If instead you really mean that you need to do

    A
    B
    B
    A
    

    (pattern repeating every 4th row, in essence), then a clear and reasonable approach is:

    $row = 0;
    foreach ($posts as $post) {
      $temp = $row%4;
      if ($temp == 0 || $temp == 3 ) echo "A
    "; else echo "B
    ";
      $row++;
    }
    

    This can obviously be made more compact - but I usually find that "explicit" is easier to read six months later - and the performance impact is negligible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址