<?php foreach ($fields as $id => $field): ?>
<div class="<?php print $field->class; ?>">
<?php print $field->content; ?>
</div>
<?php endforeach; ?>
循环的结果如下,
<div class="1">.....</div>
<div class="2">.....</div>
<div class="3">.....</div>
<div class="4">.....</div>
<div class="1">.....</div>
<div class="2">.....</div>
<div class="3">.....</div>
<div class="4">.....</div>
<div class="1">.....</div>
<div class="2">.....</div>
<div class="3">.....</div>
<div class="4">.....</div>
我想像这样对第一个<div>
进行分组。
<div class="group">
<div class="1">.....</div>
<div class="2">.....</div>
<div class="3">.....</div>
</div>
<div class="4">.....</div>
如何制作foreach
答案 0 :(得分:2)
应该相似,只需使用foreach
代替for
<style>
.group{
background: red;
margin-top: 10px;
float: left;
}
</style>
<?php $count=0; ?>
<?php for($i=0; $i<= 20; $i++): ?>
<?php if($count == 0): ?>
<div class="group">
<?php endif; ?>
<?php $count++ ?>
<div class="<?php echo $i; ?>"><?php echo $i; ?></div>
<?php if($count == 4): ?>
<?php $count=0; ?>
</div>
<?php endif; ?>
<?php endfor; ?>
答案 1 :(得分:1)
如果$field->class
变量的范围始终为1到4,则可以执行以下操作。否则你需要使用手动计数器。
<?php foreach ($fields as $id => $field): ?>
<?php if ($field->class == 1) :?> <div class="group"> <?php endif; ?>
<div class="<?php print $field->class; ?>">
<?php print $field->content; ?>
</div>
<?php if ($field->class == 4) :?> </div> <?php endif; ?>
<?php endforeach; ?>
自定义计数器
<?php $counter = 0; ?>
<?php foreach ($fields as $id => $field): $counter++;?>
<?php if ($counter == 1) :?> <div class="group"> <?php endif; ?>
<div class="<?php print $field->class; ?>">
<?php print $field->content; ?>
</div>
<?php if ($counter == 4) : $counter = 1?>
</div>
<?php endif; ?>
<?php endforeach; ?>
答案 2 :(得分:1)
尝试(原始代码)
<div class="group">
<?php $c=0; foreach ($fields as $id => $field) : ?>
<?php if($c%3==0) : ?> </div><div class="group"><?php endif; ?>
<div class="<?php print $field->class; ?>">
<?php print $field->content; ?>
</div>
<?php $c++; endforeach; ?>
</div>