使用PHP foreach将类添加到div

时间:2018-08-19 22:30:53

标签: php

考虑以下类数组:

$array =['blue', 'gren', 'red', 'orange', 'yellow', 'pink'];

我需要每个div都有一个课程:

foreach ($array as $div) {
    echo '<div class="">'.$div.'</div>';
}

我需要的示例:

<div class="first">blue</div>
<div class="second">gren</div>
<div class="last">red</div>

<div class="first">orange</div>
<div class="second">yellow</div>
<div class="last">pink</div>

假设我在一个数组中有100条记录。

first
second
last

first
second
last

first
second
last

first
second
last

Etc.

3 个答案:

答案 0 :(得分:0)

如果我正确理解了您的要求,则应该可以通过以下代码来实现。 考虑跟踪迭代的当前索引($i),以确定要应用于div的类。注意,我将模运算符%switch块一起使用来决定每次迭代使用哪个类:

$i = 0;

foreach ($array as $div) {

    $i++;

    $class = "";
    switch ($i % 3) {
        case 0:
            $class = "first";
            break;
        case 1:
            $class = "second";
            break;
        case 2:
            $class = "third";
            break;
    }

    echo '<div class="'.$class.'">'.$div.'</div>';
}

答案 1 :(得分:0)

foreach ($array as $n => $div) {
    if ($n % 3 == 0) $pos = 'first';
    elseif ($n % 3 == 1) $pos = 'second';
    else $pos = 'last';

    echo '<div class="' . $pos . '">'.$div.'</div>';
}

答案 2 :(得分:0)

您可以使用first运算符简单地使用数组索引来检查它是secondlast还是% div。例如:

foreach ($array as $i => $div) {
    if ($i % 3 == 0) {
        $class = 'first';
    } elseif ($i % 3 == 1) {
        $class = 'second';
    } else {
        $class = 'last';
    }
    echo "<div class='$class'>$div</div>";
}