确定项目在网格中显示时的余数 - PHP

时间:2012-09-03 12:33:38

标签: php modulus

我有一个循环,一次显示最多12个项目的网格中的项目(3个横跨4行向下)。网格中可以有任意数量的项目(1到12),但是在一行中只有1个或2个项目的实例上,我需要在HTML中附加一个类。例如:

当我有3,6,9,12项时 - 不需要任何东西 当我有4,7,10项(1个余数)时 - 第4,7和10项需要上课 当我有5,8,11项(剩余2项)时 - 项目4,5,7,8,10,11需要上课

我如何在PHP中执行此操作。我对每个项目都有以下内容:

  • 页面上的产品总数
  • 当前项目

道歉 - 编辑器伪代码伪代码:

$howmanyleft = totalproducts - currentproduct
if ($howmanyleft <= 2) {
    if ($currentproduct % 3 == 0) {
        //addclass
    }
}

然后在我的CSS中

article.product-single  {
    width: 33.3333%;
    border-bottom: 1px solid rgb(195,195,195);
    border-right: 1px solid rgb(195,195,195);
}
article.product-single:nth-child(3n) {
    border-right: none;
}

article.lastrow, article.product-single:last-child {
    border-bottom:none;
}

对不起,我错了。这不是我需要的。我很抱歉。我只需要用类标记任何剩余的项目,而不是每一行。

如果有4个项目,则第4项会被标记 如果有5个项目,则第4项和第5项会被标记 如果有10个项目,则项目10会被标记 如果有11个项目,则项目10和11会被标记

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你需要一些如下代码:

// check how many items will remain in the final row (if the row is not filled with 3 items)
$remainder = $total_items % 3;
for ($i = 0; $i < $total_items; $i++) { 
    if($remainder > 0 && $i >= $total_items - $remainder) {
        // executed for items in the last row, if the number of items in that row is less than 3 (not a complete row)
    } else {
        // executed for items that are in 3 column rows only
    }
}

这是一个完整的例子,说明这样的事情是如何运作的。使用以下代码创建一个新的php文件并查看输出。

// add some random data to an array
$data = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven');
$total_items = count($data);

// check how many items will remain in the final row (if the row is not filled with 3 items)
$remainder = $total_items % 3;

// loop through all the items
for ($current_item = 0; $current_item < $total_items; $current_item++) { 
// check to see if the item is one of the items that are in the row that doesn't have 3 items
    if($remainder > 0 && $current_item >= $total_items - $remainder) {
        echo $data[$current_item] . " - item in last row, when row is not complete<br />";
    // code for regular items - the ones that are in the 
    } else {
        echo $data[$current_item] . " - item in filled row<br />";
    }
}

答案 1 :(得分:0)

这只是number_of_products modulo number_of_columns

4 % 3 == 1
5 % 3 == 2
6 % 3 == 0