首页 > 解决方案 > PHP:为每个循环添加一个新的 div

问题描述

我想要做的是为每个循环添加一个新的 div。

<?php
 $f_count = 0; //Is this right?
 foreach ($this->items as $item) {
  <div>
   //stuff
  </div>
  if ($f_count++ == 1) { //Is this right?
   //mystuff1 here 
  }
  if ($f_count++ == 2) { //Is this right?
   //mystuff2 here 
  }
 }
?>

所以每个循环都需要有一个我在“mystuff”中创建的菜单项。问候!

标签: phploopsforeachcount

解决方案


好像你想要这样的东西,重要的部分是:

  • 使用 $key => $item,$key 将是 0,1,2,3,4,所以基本上是一个计数器供您使用!
  • 您可以检查是否是 1,3,5 使用if ($key %2 === 1), 和 0,2,4,6 使用if ($key %2 === 0)
  • 您需要在 HTML 元素之前关闭 PHP 标记

================

<?php
 //$f_count = 0; //No need this

 $items = ["first", "second", "third"];//I used $items, you can keep using $this->items
 foreach ($items as $key => $item) {
  ?>
  <div>
   //stuff
  </div>
<?php
  if ($key %2 === 1) { //1,3,5,7......
?>
<div>
 //mystuff1 here 
</div>
<?php   
  } else { //2,4,6,8
?>  
<div>
   //mystuff2 here 
</div>
<?php  
  }
 }
?>

推荐阅读