我正在做一个foreach,我想跳过前六个条目。到目前为止我有这个,它只是输出相同的一个,对于剩下的条目数,我应该把if($i2==6) continue;
放在其他地方吗?
<?php
$features = $property->get_features();
if($lastRec2=count($features)){
echo '<div class="row">';
$i2=0;
foreach($features as $feature2) {
$i2++;
if($i2==6) continue;
if( ($i2 % 3== 1) && ($i2<$lastRec2) ) echo '</div><div class="row">';
echo '<div class="col-md-4 p-b-15"><div class="fa-stack fa-1x checkmark-icon"><i class="fa fa-circle fa-stack-2x icon-background"></i><i class="fa fa-check fa-stack-1x icon-text"></i></div><div class="checkmark-inner">'. $feature .'</div></div>';
}
echo '</div>';
}
?>
答案 0 :(得分:1)
答案 1 :(得分:1)
只需切换到for循环。除非你需要迭代器。
$features = $property->get_features();
if($lastRec2 = count($features)){
echo '<div class="row">';
for ($i2 = 6; $i2 < count($features); ++$i2) {
if( ($i2 % 3 == 1) && ($i2 < $lastRec2) ) echo '</div><div class="row">';
echo '<div class="col-md-4 p-b-15"><div class="fa-stack fa-1x checkmark-icon"><i class="fa fa-circle fa-stack-2x icon-background"></i><i class="fa fa-check fa-stack-1x icon-text"></i></div><div class="checkmark-inner">'. $features[$i2] .'</div></div>';
}
echo '</div>';
}
答案 2 :(得分:1)
您可以使用array_chunk
和array_slice
来完成您的目标:
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.array-chunk.php
$features = $property->get_features();
$skipped = array_slice($features, 6);
$chunks = array_chunk($skipped, 3);
foreach ($chunks as $chunk) {
echo '<div class="row">';
foreach ($chunk as $feature) {
echo '<div class="col-md-4 p-b-15"><div class="fa-stack fa-1x checkmark-icon"><i class="fa fa-circle fa-stack-2x icon-background"></i><i class="fa fa-check fa-stack-1x icon-text"></i></div><div class="checkmark-inner">' . $feature . '</div></div>';
}
echo '</div>';
}
或者,如果您希望使用HTML可以使您的代码更具可读性:
foreach ($chunks as $chunk) : ?>
<div class="row">
<?php foreach ($chunk as $feature) : ?>
<div class="col-md-4 p-b-15">
<div class="fa-stack fa-1x checkmark-icon">
<i class="fa fa-circle fa-stack-2x icon-background"></i>
<i class="fa fa-check fa-stack-1x icon-text"></i>
</div>
<div class="checkmark-inner">
<?php echo $feature ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach;
仅供参考,我假设$feature2
你的问题是一个错字。如果不是让我知道哪个变量是什么意思,我会更新我的答案。
希望这有帮助!
答案 3 :(得分:0)
首先,如果你想删除前六个条目,你的if是错误的,应该是:
if($i2 <= 6) continue;
如果数组中的键是顺序键,你可以这样做:
foreach($features as $key => $feature2) {
if($key < 6) continue;//0 to 5
除非您的代码仍然有用