考虑一下这个类的数组:
$array =['blue', 'gren', 'red', 'orange', 'yellow', 'pink'];
我需要每个div
都有一个类:
foreach ($array as $div) {
echo '<div class="">'.$div.'</div>';
}
我需要的示例:
<div class="first">blue</div>
<div class="second">gren</div>
<div class="last">red</div>
<div class="first">orange</div>
<div class="second">yellow</div>
<div class="last">pink</div>
假设我在一个数组中有100条记录。
first
second
last
first
second
last
first
second
last
first
second
last
Etc.
发布于 2018-08-20 06:46:19
foreach ($array as $n => $div) {
if ($n % 3 == 0) $pos = 'first';
elseif ($n % 3 == 1) $pos = 'second';
else $pos = 'last';
echo '<div class="' . $pos . '">'.$div.'</div>';
}
发布于 2018-08-20 06:45:17
如果我正确理解了您的要求,这应该可以通过以下代码来实现。考虑跟踪迭代的当前索引($i
),以确定要应用于div的类。请注意,我在switch
块中使用了模运算符%
来决定每次迭代使用哪个类:
$i = 0;
foreach ($array as $div) {
$i++;
$class = "";
switch ($i % 3) {
case 0:
$class = "first";
break;
case 1:
$class = "second";
break;
case 2:
$class = "third";
break;
}
echo '<div class="'.$class.'">'.$div.'</div>';
}
发布于 2018-08-20 06:46:27
您可以简单地使用数组索引来检查它是first
、second
还是last
div,使用%
运算符。例如:
foreach ($array as $i => $div) {
if ($i % 3 == 0) {
$class = 'first';
} elseif ($i % 3 == 1) {
$class = 'second';
} else {
$class = 'last';
}
echo "<div class='$class'>$div</div>";
}
https://stackoverflow.com/questions/51922337
复制相似问题