我如何在PHP foreach循环中交替div元素 [英] How can I alternate div elements in php foreach loop
问题描述
我从数据库中获得一组数组,我使用一个php foreach
循环来完成它们。如果我返回5个数组 [1,2,3,4,5]
,每个数组都包含一个(时间,状态,位置),我想对所有偶数组与一个特定的div和每个奇数与不同的div。我会如何做到这一点?
我假设我将使用带模运算符的循环。
<$ p $ ($ i%2 == 0){
}为$($ i = 1; $ i <= $ count; $ i ++)
的
$ hr
<?php foreach($ reservation as $ seat):?>
如果是数组1,3,5。
< div style =font-size:20px; background-color:#red; float:left;>
<?php echo $ seat ['location']; ?>
<?php echo $ seat ['time']; ?>
<?php echo $ seat ['status']; ?> < / DIV>
如果是数组2,4
< div style =font-size:20px; background-color:#blue; float:right;>
<?php echo $ seat ['location']; ?>
<?php echo $ seat ['time']; ?>
<?php echo $ seat ['status']; ?> < / DIV>
<?php endforeach?>
解决方案您不必使用foreach循环来枚举数组的所有元素:
pre $ code> for($ i = 1; $ i <= $ count; $ i ++){
$ seat = $ reservation [$ i-1];
if($ i%2 == 0){
//做你的2和4
} else {
//做你的1,3和5
}
}
我建议设置CSS类为odd和even到divs,然后在一个单独的文件中设置它们的样式。如果你愿意,你也可以使用CSS3伪类:nth-child(odd)
和:nth-child(偶数)
。
I have a set of arrays I'm getting back from the database, I'm using a php foreach
loop to go through them. If I'm returning 5 arrays [1, 2, 3, 4, 5]
, each one containing a (time, status, location) I want to style all even arrays with a certain div and each odd ones with a different div. How would I do this?
I'm assuming I would use the loop with modulo operator.
for ($i = 1; $i <= $count; $i++)
if ($i % 2 == 0) {
} else {
}
}
<?php foreach ($reservation as $seat) : ?>
If it is array 1, 3, 5.
<div style="font-size:20px; background-color: #red; float:left;">
<?php echo $seat['location']; ?>
<?php echo $seat['time']; ?>
<?php echo $seat['status']; ?> </div>
If it is array 2, 4
<div style="font-size:20px; background-color: #blue; float:right;">
<?php echo $seat['location']; ?>
<?php echo $seat['time']; ?>
<?php echo $seat['status']; ?> </div>
<?php endforeach ?>
You do not have to use a foreach loop to enumerate all elements of an array:
for ($i=1; $i <= $count; $i++) {
$seat = $reservation[$i-1];
if ($i % 2 == 0) {
// Do your 2 and 4
} else {
// Do your 1, 3 and 5
}
}
I'd recommend setting CSS-classes "odd" and "even" to the divs and then style them in a separate file. If you want, you can also use CSS3 pseudo classes :nth-child(odd)
and :nth-child(even)
.
这篇关于我如何在PHP foreach循环中交替div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!