为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁星coding 2022-06-17 16:36:33
我正在尝试根据每个包装块的结果数添加一些自定义类。在每个包装块的最后一个添加类last。计算每个包装块的结果,并根据结果添加自定义类,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>
查看完整描述

1 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

这可能最容易通过将数组拆分为块并在循环中单独处理每个块,使用count块的 来决定将哪个类添加到跨度:


$array = range(1, 11);

$chunks = array_chunk($array, 4);


$span_classes = ['', 'one-half', 'one-third', 'one-fourth'];


foreach ($chunks as $chunk) {

    echo "<div class=\"item\">\n";

    $count = count($chunk);

    $span_class = $span_classes[$count-1];

    for ($i = 0; $i < $count; $i++) {

        $last = $i == $count - 1 ? ' last' : '';

        $val = $chunk[$i];

        echo "<span class=\"$span_class$last\">$val</span>\n";

    }

    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>


查看完整回答
反对 回复 2022-06-17
  • 1 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信