我需要为foreach循环中的每6个div提供一个不同的类名。我认为我的下面的想法会起作用,但每个项目似乎都得到相同的div。
<?php $num = 0; ?>
<?php foreach ($divs as $div): ?>
<?php if($num % 1 == 0): ?>
<div class="threecol grey one">
<?php elseif($num % 2 == 1): ?>
<div class="threecol green two ">
<?php elseif($num % 3 == 2): ?>
<div class="sixcol blue last three">
<?php elseif($num % 4 == 3): ?>
<div class="threecol grey">
<?php elseif($num % 5 == 4): ?>
<div class="sixcol blue">
<?php elseif($num % 6 == 5): ?>
<div class="threecol green last">
<?php endif; ?>
Rest of html
</div>
<?php $num++ ?>
<?php endforeach; ?>
为了简化我基本上需要
1st / 7th / 13th / 19th ... etc div为<div class="threecol grey">
2月8日/ 14日/ 20日......等<div class="threecol green">
3 / 9th / 15th / 21st ...等<div class="sixcol blue last">
4th / 10th / 16th / 22nd <div class="threecol grey">
5th / 11th / 17th / 23rd <div class="sixcol blue">
6th / 12th / 18th / 24th <div class="sixcol blue">
答案 0 :(得分:1)
非常难看......为什么不
$classes = array('grey one', 'green two', 'blue last three', 'grey', 'blue', 'green last');
foreach($divs as $div) {
$class = $classes[$i++ % 6];
echo '<div class="threecol ' . $class . '">';
}
主要问题是你在模运算中不断改变除数,所以你总是得到0余数。
答案 1 :(得分:1)
你误解了模运算符,导致了红利的剩余部分。因此,% 1
总是为零,因为该操作永远不会有余数。你想这样做:
$num % 6 == 1
...
$num % 6 == 2
等。您也可以提前$num % 6
并将其存储在变量中。
答案 2 :(得分:0)
<?php if(floor($num / 6) == 0): ?>
<div class="threecol grey one">
<?php elseif(floor($num / 6) == 1): ?>
<div class="threecol green two ">
<?php elseif(floor($num / 6) == 2): ?>
<div class="sixcol blue last three">
<?php elseif(floor($num / 6) == 3): ?>
<div class="threecol grey">
<?php elseif(floor($num / 6) == 4): ?>
<div class="sixcol blue">
<?php elseif(floor($num / 6) == 5): ?>
<div class="threecol green last">
<?php endif; ?>
这会给:
threecol grey one
表示0到5之间的列threecol grey two
适用于6到11列答案 3 :(得分:0)
<?php foreach ($divs as $i => $div): ?>
<?php if($i % 6 == 0): ?>
<div class="threecol grey one">
<?php elseif($i % 6 == 1): ?>
<div class="threecol green two ">
<?php elseif($i % 6 == 2): ?>
<div class="sixcol blue last three">
<?php elseif($i % 6 == 3): ?>
<div class="threecol grey">
<?php elseif($i % 6 == 4): ?>
<div class="sixcol blue">
<?php elseif($i % 6 == 5): ?>
<div class="threecol green last">
<?php endif; ?>
Rest of html
</div>
<?php endforeach; ?>
考虑使用switch case语句。