dshgdhdfcas30210 2018-08-07 09:03
浏览 85
已采纳

循环中的php模数,每行只显示5个项目

I want to loop extra deetails.. by calculate the total items divided five. For example, i have 2 items, then i will add extra 3 div to it. When i have 8 items, i will add extra 2 div to it.

$totalcount = 2;
$check = $totalcount %5;
$totalcount = 8;
$check = $totalcount %5;

I found out i cant use this method because it loops wrongly. i will use extra loop to show the result when detect the main loop when reached end of loop.

if($key == $len - 1)
    for ($i = 0; $i < $check; $i++) {
        // do something
    }
}

Is there any solution, i can ensure $totalcount%5 is always equal to zero and add extra div details to it?

  • 写回答

1条回答 默认 最新

  • douzongluo7542 2018-08-07 09:38
    关注

    You have to do little bit of calculation to find out extra number of divs required. Given the fact that $totalcount is your number of rows, $totalcount would be your necessary number of divs. And subsequently you would have to calculate extra number of divs in the following way,

    $totalcount = 7; // or some other value
    $totaldivs = $totalcount + (5 - ($totalcount % 5));
    $extradivs = $totaldivs - $totalcount; // extra divs
    

    Finally you can use two loops, one printing actaul rows inside divs and other printing extra divs, like this:

    // loop printing rows inside divs
    for($i = 0; $ < $totalcount; ++$i){
        echo '<div>';
        // your rows
        echo '</div>';
    }
    
    // loop printing extra divs
    for($i = 0; $ < $extradivs; ++$i){
        echo '<div>';
        ...
        echo '</div>';
    }
    

    Sidenote: I kept if($key == $len - 1){ ... } block outside of the equation but you can place it in the appropriate place as per your requirement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿