Need a little help with a solution for this problem. I have a list of services that is generated as such:
<div class="row">
<?php foreach( $entries as $s ) : ?>
<?php require( dirname(__FILE__) . '/_index_DisplayService.php' ); ?>
<?php endforeach; ?>
</div>
_index_DisplayService.php
<div class="grid-4">
<div id="service-mobile-dev" class="service">
<div class="service-icon">
<i class="icon-calendar"></i>
</div>
</div>
</div>
Now this is a grid-12 layout, so I need 3, grid-4 per row then new row. I think that a solution starts with moving the <div class="row">
below <?php foreach( $entries as $s ) : ?>
looking something like this:
<?php foreach( $entries as $s ) : ?>
<div class="row">
<?php require( dirname(__FILE__) . '/_index_DisplayService.php' ); ?>
</div>
<?php endforeach; ?>
This of course kicks everything to a single row. How do I go about generating 3 grid-4's per row.
Thanks!
You can use the index => value
properties in a foreach
(or replace it entirely with a for
loop) and run a modulo on the index to insert the row div conditionally. Assuming $entries
is an array
.
<?php
foreach ($entries as $key => $value) :
// Close the "previous" row tag before beginning the next row
// Obviously we should not start with a closing tag ($key > 0)
if ($key > 0 && $key%3 == 0) {
?>
</div>
<?php
}
// Start a new row
if ($key%3 == 0) {
?>
<div class="row">
<?php
}
// Insert the "grid-4" elements
require( dirname(__FILE__) . '/_index_DisplayService.php' );
endforeach;
// If there were any entries then we have a row which hasn't been closed yet.
// Close it.
if (count($entries) > 0) {
?>
</div>
<?php
}
?>
Assuming that $entries
is an indexed array, $ind%3
will be 0 when $ind
is 0,3,6 and 9.
<?php foreach( $entries as $ind=>$s ) : ?>
<?if($ind%3==0){?><div class="row"><?}?>
<?php require( dirname(__FILE__) . '/_index_DisplayService.php' ); ?>
<?if($ind%3==0){?></div><?}?>
<?php endforeach; ?>
To do this you need to set a counter. I added a fake array that represent your entries, so you can test it as is. As I wrote this, it looks like some others posted some really great answers as well. Good luck!
$entries = array(
'entry-one',
'entry-two',
'entry-three',
'entry-four',
'entry-five',
'entry-six'
);
$counter = 0;
foreach( $entries as $s ) {
if( $counter > 2 ) {$counter = 0;}
if( $counter === 0 ) {
echo '<div class="row">' ;
}
echo '
<div class="grid-4">
<div id="service-mobile-dev" class="service">
<div class="service-icon">
<i class="icon-calendar"></i>'
. $s .'
</div>
</div>
</div>';
if( $counter === 2) {
echo "</div>";
}
$counter++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.