首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >排版在foreach php中使用类名

排版在foreach php中使用类名
EN

Stack Overflow用户
提问于 2016-08-15 02:13:02
回答 1查看 125关注 0票数 2
代码语言:javascript
复制
<?php
  $classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');

  if($productCatalogs != null){

    $i = 0;

    foreach($productCatalogs as $productCatalog){

      $i++;

      if($i % 2 == 0){

        // if $i is even number
        echo '<li class="{ use classname here }"><a href="#">Link name</a></li>';

      } else {

        // if $i is odd number
        echo '<li><a href="#">Link name</a></li>';

      }

    }

  }
?>

正如上面的代码所示,当$classNames仅为偶数时,我希望在$i中使用每个$i值,比如第一次偶数记录使用{DURBER-2 },然后偶数记录使用{ above 4 }。

下面是我想要的代码结果,

代码语言:javascript
复制
<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-4"></li>

<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-8"></li>

<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-4"></li>

...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-15 02:32:05

只需在数组中使用一个计数器变量作为索引,并在找到偶数number.Also时进行增量,如果您有许多元素,则需要检查是否到达数组的末尾,并按如下方式重置counter.Something:

代码语言:javascript
复制
    <?php
  $classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');

  if($productCatalogs != null){

    $i = 0;
    $even_counter=0;

    foreach($productCatalogs as $productCatalog){

      $i++;

      if($i % 2 == 0){

         // if $i is even number
    echo '<li class="'.$classNames[$even_counter].'"><a href="#">Link name</a></li>';

    //when we reach the end of the array we reset our counter to 0
    $even_counter=($even_counter+1==count($classNames))?0:$even_counter+1;
      } else {

        // if $i is odd number
        echo '<li><a href="#">Link name</a></li>';

      }

    }

  }
?>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38948434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档