Reputation: 31347
I wish to display a (flat) list of records in chunks of 3 items like this:
<div class="wrapper">
<div id="item1"></div>
<div id="item2></div>
<div id="item3"><div>
</div>
<div class="wrapper">
<div id="item4"></div>
<div id="item5></div>
<div id="item6"><div>
</div>
Those item1 to n will be retrieved from a db query.
The problem are the wrapper divs.
It seems I need to slit a foreach
in n chucks?
Can I have a little push here?
Upvotes: 1
Views: 57
Reputation: 120684
<?php
function renderWrapperStart($i) {
if ($i % 3 !== 0) {
return;
}
?>
<div class="wrapper">
<?
}
function renderWrapperEnd($i) {
if ($i % 3 !== 0 || $i == 0) {
return;
}
?>
</div>
<?
}
function renderItem($i, $id, $content) {
?>
<div id="<?= $id ?>"><?= $content ?></div>
<?
}
$items = array(
'item1' => 'content 1',
'item2' => 'content 2',
'item3' => 'content 3',
'item4' => 'content 4',
'item5' => 'content 5',
'item6' => 'content 6'
);
$i = 0;
foreach ($items as $id => $content) {
renderWrapperEnd($i);
renderWrapperStart($i);
renderItem($i, $id, $content);
$i++;
}
renderWrapperEnd($i);
?>
Output is:
<div class="wrapper">
<div id="item1">content 1</div>
<div id="item2">content 2</div>
<div id="item3">content 3</div>
</div>
<div class="wrapper">
<div id="item4">content 4</div>
<div id="item5">content 5</div>
<div id="item6">content 6</div>
</div>
Upvotes: 1
Reputation: 18521
$end = 20;
for($count = 1; $count <= $end; $count++){
if(($count % 3) == 1)
echo '<div class="wrapper">';
echo '<div id="item'.$count.'"></div>';
if(($count % 3) == 0 || $count == $end)
echo '</div>';
}
EDIT (separated the HTML from PHP per request in comments):
$end = 20;
for($count = 1; $count <= $end; $count++){
if(($count % 3) == 1){
?>
<div class="wrapper">
<?php
}
?>
<div id="item<?=$count?>"></div>
<?php
if(($count % 3) == 0 || $count == $end){
?>
</div>
<?php
}
}
Upvotes: 3
Reputation: 5752
is this what you want ?
for($i=1 ; $i<= n ; $i++){
if($i%3 == 0) {
echo '<div class="wrapper">';
}
echo '<div id="item'.$i.'"></div>';
if($i%3 == 0) {
echo '</div>';
}
}
Upvotes: -1
Reputation: 603
Do you mean ?
array_chunk($arr, 3);
http://www.php.net/manual/en/function.array-chunk.php
Upvotes: -2