我有一个简单的for循环,它显示li元素。
for($rn = 1; $rn <= $total; $rn++){
echo '<li>this is a li element</li>';
}
总数是李的总数。
李向左浮动,每行显示6个李,每个李都有一个底部边界。
我希望使用php通过添加一个span类来删除最后一行中li的边界。
这有点棘手,因为假设我有15排。
我需要一个php代码,它将从15减去12,并将无边界类添加到最后3个li。
我的想法是:将$total除以6,并将结果四舍五入。15:6=2.5四舍五入,但记住较小的值-将为2。
10将2乘以6,从15减去12,得到3行。
有什么想法吗
模运算符%
通过将两个数字除得出余数。
15 % 6 == 3
$totalRows % $itemsPerRow
我会这样解决它:
for($rn = 1, $end = ( 0 == ( $temp = $total % 6) ? $total - 6 : $total - $temp ); $rn <= $total; $rn++) {
if ($end < $rn) {
// no border
}
}
基本上,它检查它是否可以除以6。如果没有休息,最后六个元素就没有边界。如果有rest,则只有最后一行中的元素没有边界。
优点是,它不会调用循环之外的任何变量。
循环未测试,计算已测试。
$remainder = $total % 6; // Get your remainder, number of li on the last row.
for($rn = 1; $rn <= $total; $rn++){
// If the the total minus the number of li's output is less than or equal to remainder your outputting the last row.
if($total - $rn <= $remainder)
{
echo '<li class=''borderless''>this is a li element</li>';
}else{
echo '<li>this is a li element</li>';
}
}
- 请注意,这是未经测试的
$bottom = $total % 6;
$bottom = $bottom ? $total - $bottom : $total - 6;//calculate values in the last row
for($rn = 1; $rn <= $total; $rn++){
$class = $rn > $bottom ? ' class="span"' : '';//if rn is in the last row add span calss
echo "<li$class>this is a li element</li>";
}