PHP - 在foreach循环中在2到3个div之间切换

时间:2017-09-07 18:15:00

标签: php twitter-bootstrap modulus

我想使用twitter bootstrap在php中循环foreach,其结果将是这样的。 我已经尝试过很多模数等方法,有人可以帮帮我吗?

    <div class="row">
        <div class="col-md-6">Item 1</div>
        <div class="col-md-6">Item 2</div>
    </div>
    <div class="row">
        <div class="col-md-4">Item 3</div>
        <div class="col-md-4">Item 4</div>
        <div class="col-md-4">Item 5</div>
    </div>
    <div class="row">
        <div class="col-md-6">Item 6</div>
        <div class="col-md-6">Item 7</div>
    </div>
    <div class="row">
         <div class="col-md-4">Item 8</div>
         <div class="col-md-4">Item 9</div>
         <div class="col-md-4">Item 10</div>
    </div>

等等。 提前谢谢

  • 我使用了翻译,对不起!

2 个答案:

答案 0 :(得分:2)

$numRows = 4;
$content = "";

for ($i = 1; $i <= $numRows; $i++) {
    (($i % 2) == 0) ? $k = 2 : $k = 3;

    $content .= "<div class='row'>";

    for ($j = 1; $j <= $k; $j++) {
        $content .= "<div class='col-md" . ($k * 2) . "'>Item " . $j . "</div>";
    }

    $content .= "</div>";
}

echo $content;

答案 1 :(得分:0)

假设您从一组数据输出,这是一种方法:

foreach (array_chunk($your_data, 5) as $row_set) {
    $first_row = array_splice($row_set, 0, 2); // iterate this and output as col-md-6
    $row_set;  //iterate what's left (if anything) and output as col-md-4
}

输出HTML的确切方式取决于您。