如何缩短 PHP 行?

How can I make this PHP lines shorter?

我同时有这个循环,它将计算输出:

while ($wp_query->have_posts()) : $wp_query->the_post(); $current++; $current2++;

然后调用正确的 html class 我的设计需要这个:

<div class="span4 <?php if($current == 0) { echo 'first'; } elseif($current == 1) { echo 'second'; } elseif($current == 2) { echo 'first'; } elseif($current == 3) { echo 'second'; } ?>" id="<? echo $current; ?>">

$count从0开始,$count2从1开始。输出应该是这样的:if 0=first, 1=second, 2=first, 3=second 等等。如何使用无限数量的 $count 缩短此表达式?我希望我的问题很清楚。在这里感谢那些愿意帮助我的人。

如果我明白你在这里问什么,我想你想用'first'和'second'交替你的div 类?

因此,您可以使用 % 模运算符(参见 http://php.net/manual/en/internals2.opcodes.mod.php

<div class="span4 <?php echo ($current % 2 === 0 ? 'first' : 'second'); ?>" id="<? echo $current; ?>">

试试这个方法

<div class="span4 
 <?php if ($curent%2 == 0){ echo 'first'; } 
  else {echo 'second';}?> id="<? echo $current; ?>"> 

因此您可以使用 mod - 最好为 WordPress 使用完整的<?php 标签,如果它是这样的话。

php test if number is odd or even

    // set up the html clips
    if($current % 2 == 0){
    $html_clips = 'first'; 
    }else{
    $html_clips = 'second'; 
    }
    if($current == 0) $html_clips = 'first';
    <div class="span4 <?php echo $html_clips ?>" id="<?php echo $current; ?>">

如果您只是将这些 class 名称用于交替 CSS 样式,可以使用 CSS3

你的HTML

<div class="span4" id="<? echo $current; ?>">

并且在您的 css 文件中

.span4:nth-child(even) {background: #CCC}
.span4:nth-child(odd) {background: #FFF}

否则,对于 PHP 解决方案,Liam Wiltshire 的回答应该很好用。

来源:CSS even and odd rules examples