breaking output of php array into chunks
I have an array containing information about some images, which I am using to print a number of img html tags by a foreach loop as follows:
<?php foreach ( $images as $image ) : ?>
<img alt="<?php echo $image->alttext ?>" src="<?php echo $image->thumbnailURL ?>" /开发者_运维百科>
<?php endforeach; ?>
I would like to wrap a div around every 10 images. The remainder should get a div as well.
I am thinking I need to use array_chunk
on $images
and wrap the above in another loop for each chunk. The little bit of math I did to start is as follows:
$pics_per_page = 10;
$imgcount = count($images);
$num_pages = ceil($imgcount/$pics_per_page);
$pages = array_chunk($images, $num_pages);
How do I proceed from here? How do I use the $images array correctly, if at all, in outputting my HTML?
Forgetting about the array_chunk method, I have the following way, but the array_chunk method seems cleaner.
for i from 1 to num_pages:
echo "<div>"
j = (i-1) * pics_per_page;
while j <= i * pics_per_page
echo "<img src = "$images[j]->thumbnailURL />";
endwhile;
echo "</div>"
Thanks for your help in advance, Sepehr
You are using array_chunk
[docs] wrongly. You just have to specify the size of each chunk:
$chunks = array_chunk($images, 10);
Then you need a nested for
(foreach
) loop:
<?php foreach($chunks as $chunk): ?>
<div class="someClass">
<?php foreach($chunk as $image): ?>
<img alt="<?php echo $image->alttext ?>" src="<?php echo $image->thumbnailURL ?>" />
<?php endforeach; ?>
</div>
<?php endforeach; ?>
You could use it without array_chunk
too.
<?php
$imgTot = count($images);
echo '<div>';
for($i=0; $i<$imgTot; $i++)
{
if ($i % 10 == 0) {
echo '<div>';
}
echo '<img alt="'.$image->alttext.'" src="'.$image->thumbnailURL.'" />';
if ($i % 10 == 9) {
echo '</div>';
}
}
echo '</div>';
?>
See the working example here: http://codepad.org/FkdTEH91
精彩评论