每个人都知道如何在foreach循环中每n次迭代输出一点html。
$i=0;
foreach($info as $key){
if($i%3 == 0) {
echo $i > 0 ? "</div>" : ""; // close div if it's not the first
echo "<div>";
}
//do stuff
$i++;
}
我正在尝试做同样的事情,但我不是$i的已知值,而是从类似
Array(0=>2, 1=>1, 2=>5)
这样而不是
<div>
item
item
item
</div>
<div>
item
item
item
</div>
<div>
item
item
item
</div>
我可以得到这样的东西:
<div>
item
item
</div>
<div>
item
</div>
<div>
item
item
item
item
item
</div>
但我就是无法让它工作。我想我已经很接近了,但有些东西正在逃避我。有什么想法吗?
这是我现在正在运行的代码:
//$footnote = array of values
$i=0;
$m=0;
$bridge .= '<div class="grid block menu">';
foreach($value['sections'] as $section) {
if ($i++%$footnote[$m] === 0) {
$bridge .= '</div><div class="grid block menu">';
$m++;
}
$secname = $section['name'];
$dishcount = count($section['items']);
$bridge .= '<h3>'. $secname .' '.$footnote[0].'</h3>';
$i++;
} //end section foreach
$bridge .= '</div>';
我认为您遇到的问题出在代码的if($i++%...)
部分。
无需递增$i
并检查模块化表达式的结果,只需检查是否$i == $footnote[$m]
,然后在成功时将$i
重置回 0。
我在本地修改了您的脚本,请尝试一下:
$i = $m = 0;
$bridge .= '<div class="grid block menu">';
foreach($value['sections'] as $section)
{
if ($i == $footnote[$m])
{
$bridge .= '</div><div class="grid block menu">';
$m++;
$i = 0;
}
$secname = $section['name'];
$dishcount = count($section['items']);
$bridge .= '<h3>'. $secname .' '.$footnote[$m].'</h3>';
$i++;
}
$bridge .= '</div>';
这样,您实际上是遍历每个脚注,而不仅仅是检查它是否可以被指定的数字整除。
未经测试的代码,如果需要进行任何更改,请告诉我,以便我可以适当地更新答案。
// Calculate section breaks
$sections = [ 2, 1, 5];
$sectionBreaks = [];
$sum = 0;
foreach ($sections as $section) {
$sum += $section;
$sectionBreaks[] = $sum;
}
// Add the items to each section
$results = [];
$result = '';
$i = 0;
foreach ($items as $item) {
if (array_search($i, $sectionBreaks) !== false) {
$results[] = $result;
$result = '';
}
$result .= '<h3>' . $item . '</h3>';
}
// Collapse it all together
$finalResult = '<div>' . implode('</div><div>', $results) . '</div>';
这是循环
遍历数据以实现您最初公开的示例的方法。 foreach
和for
.这有效,但除非您给我们一些数据,否则我将无法对其进行调整。
$bridge='';
foreach($value['sections'] as $section) {
$bridge .= '<div class="grid block menu" number="'.$section.'"><h3>MY TITLE!! '. $section['name'] .'</h3>';
for ($x = 0; $x <= $section; $x++) {
$bridge .= "Here goes the content; Item $x<br>";
}
$bridge .= '</div>';
}
echo $bridge;
我希望它对:)有所帮助