如何缩短PHP行?

时间:2015-11-14 22:18:42

标签: php loops count alternate

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

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

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

<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的无限数量缩短此表达式?我希望我的问题很明确。感谢那些在这里帮助我的人。

4 个答案:

答案 0 :(得分:5)

如果我理解你在这里问的是什么,我想你想用'第一'和第二类来替换你的div?

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

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

答案 1 :(得分:1)

如果您只是将这些类名称用于交替的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

答案 2 :(得分:0)

试试这种方式

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

答案 3 :(得分:0)

所以你可以使用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; ?>">