How to render fixed length rows of items
Posted on 9/3/09 by Felix Geisendörfer
if you find yourself in a situation where you need to write a template that splits up a list of items in multiple rows with each row having a fixed amount of items, here is a simple solution:
<?php while ($items): ?>
<?php for ($i = 0; ($item = array_shift($items)) && $i < 4; $i++): ?>
<?php echo $item['Item']['title']; ?>
<?php endfor; ?>
<?php endwhile; ?>
This will put 4 items in each row and a smile on your face for not having to write very ugly code to achieve the same : ).
-- Felix Geisendörfer aka the_undefined
You can skip to the end and add a comment.
I recently had to do this for something myself. Only I fill by column instead of by row. Pasting code into the comment didn't work so I made a post here.">http://mywebmind.com/how-to-render-items-into-a-fixed-number-of-columns/'>here.
until today I used the if($i%4==0) statement but this is really nice. Thanks!
Neil Crookes' idea seems as if it would be cleaner, and has the benefit of being non-destructive.
Hi Felix - thanks for the great posts -
I think that in the for loop, you should flip the order of $i less than 4 condition and the array_shift operation with each other.
Otherwise it will devour an array item each loop, i.e. when $i less than 4 fails, the array has already been shifted - right?
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.
And also: http://www.php.net/function.array_chunk and 2 nested foreach statements