猿问

php循环用div和自定义类包装每4个结果

我正在尝试根据每个包装块的结果数添加一些自定义类。

  1. 在每个包装块的最后一个添加类last

  2. 计算每个包装块的结果,并根据结果添加自定义类,one-half one-third one-fourth

这是代码:

<?php

$array = range(1, 11);


    $i= 0;

    foreach ($array as $val) {

        if ($i%4 == 0) echo '<div class="item">';

        $i++;

?>

    <span class="one-fourth"><?=$val?></span>

<?php       

        if ($i%4 == 0) echo '</div>';

    }

    if ($i%4 != 0) echo '</div>';

?>

我得到的输出:


<div class="item"> 

    <span class="one-fourth">1</span>

    <span class="one-fourth">2</span>

    <span class="one-fourth">3</span>

    <span class="one-fourth">4</span>

</div>

<div class="item"> 

    <span class="one-fourth">5</span>

    <span class="one-fourth">6</span>

    <span class="one-fourth">7</span>

    <span class="one-fourth">8</span>

</div>

<div class="item"> 

    <span class="one-fourth">9</span>

    <span class="one-fourth">10</span>

    <span class="one-fourth">11</span>

</div>

我想要的输出:


<div class="item"> 

    <span class="one-fourth">1</span>

    <span class="one-fourth">2</span>

    <span class="one-fourth">3</span>

    <span class="one-fourth last">4</span>

</div>

<div class="item"> 

    <span class="one-fourth">5</span>

    <span class="one-fourth">6</span>

    <span class="one-fourth">7</span>

    <span class="one-fourth last">8</span>

</div>

<div class="item"> 

    <span class="one-third">9</span>

    <span class="one-third">10</span>

    <span class="one-third last">11</span>

</div>


繁星coding
浏览 97回答 1
1回答

潇湘沐

这可能最容易通过将数组拆分为块并在循环中单独处理每个块,使用count块的 来决定将哪个类添加到跨度:$array = range(1, 11);$chunks = array_chunk($array, 4);$span_classes = ['', 'one-half', 'one-third', 'one-fourth'];foreach ($chunks as $chunk) {&nbsp; &nbsp; echo "<div class=\"item\">\n";&nbsp; &nbsp; $count = count($chunk);&nbsp; &nbsp; $span_class = $span_classes[$count-1];&nbsp; &nbsp; for ($i = 0; $i < $count; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $last = $i == $count - 1 ? ' last' : '';&nbsp; &nbsp; &nbsp; &nbsp; $val = $chunk[$i];&nbsp; &nbsp; &nbsp; &nbsp; echo "<span class=\"$span_class$last\">$val</span>\n";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</div>\n";}输出:<div class="item"><span class="one-fourth">1</span><span class="one-fourth">2</span><span class="one-fourth">3</span><span class="one-fourth last">4</span></div><div class="item"><span class="one-fourth">5</span><span class="one-fourth">6</span><span class="one-fourth">7</span><span class="one-fourth last">8</span></div><div class="item"><span class="one-third">9</span><span class="one-third">10</span><span class="one-third last">11</span></div>
随时随地看视频慕课网APP
我要回答