每2项不同的html类

时间:2015-08-21 08:26:56

标签: php algorithm foreach

在php中我尝试这样做:

<div class="left"> some text </div>
<div class="left"> some text </div>
<div class="right"> some text </div>
<div class="right"> some text </div>
<div class="left"> some text </div>
<div class="left"> some text </div>
<div class="right"> some text </div>
<div class="right"> some text </div>
.
.
.

我需要每两个项目使用不同的类来进行不同的html设计。

3 个答案:

答案 0 :(得分:2)

试试这个,

  $arrayX = array("left","right");
    $i = 4;
    while($i<100){
        if($i%4<2){
            echo '<div class="'.$arrayX[0].'"> some text </div>';
        }else{
            echo '<div class="'.$arrayX[1].'"> some text </div>';
        }
        $i++;
    }

答案 1 :(得分:1)

也许你可以使用这个CSS。

&#13;
&#13;
div:nth-child(4n+1), 
div:nth-child(4n+2) 
{
    background: #ff0000;
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

据推测,你有一个foreach循环遍历所有'some text'条目。你可以添加一个计数器,然后做一些简单的逻辑。

$yourtexts = array("some text","some text","some text","some text","some text","some text","some text","some text","some text");

$i=0; // counter
foreach ($yourtexts as $sometext) {
    print ($i<2) ? '<div class="left">' : '<div class="right">'; // $i<2 go left else go right
    print "$sometext</div>";
    $i++; // count
    if ($i>3) { $i=0; } // reset to zero.
}