PHP foreach with counter wrap every 3 items inside a div

时间:2015-06-15 14:36:13

标签: php

I have a PHP for each like so:

<?php
    $counter = 0;
    foreach($communities as $row => $value){
        if($counter%3){
            echo "<div class='community-images'>";
        }
        echo '<div class="col-md-3 animated" data-animation="' .
              ($counter%2? 'fadeInUp':'fadeInDown') . '" data-animation-delay="300">';
        echo '<a href="our-communities.php?newcommunity=' . $value['id'] . '">
              <img src="../images/communities/' . str_replace(" ", "-", strtolower
        ($value['name'])) . '/' . $value['logo'] . '" width="150" /></a>';  
         echo '<h4>' . $value['name'] . '</h4>';
         echo '<span><strong>Location: </strong>' . $value['locationLabel'] . '</span>';
         echo '<span><strong>Starting At: </strong>$' . number_format($value['min_home_price']) . '</span>';

        echo '</div>';
        if($counter%3){
            echo '</div>';
        }
         $counter++;
    }
 ?>

what I am trying to do is wrap 3 col-md-3 items inside community-image div once a community-image has 3 col-md-3, close the wrapper and start a new community-image wrapper for the next 3 col-md-3 items

1 个答案:

答案 0 :(得分:1)

Please change this

 if ($counter % 3){

To

 if ($counter % 3 == 0) {

The reason is ($counter % 3) always returns a number either 0 or some integer. It would be always true for if and will execute, so you must check if return is 0. So your full code will be

$counter = 0;


foreach ($communities as $row => $value) {
    if ($counter % 3 == 0) {
        echo "<div class='community-images'>";
    }
    echo '<div class="col-md-3 animated" data-animation="' . ($counter % 2 ? 'fadeInUp' : 'fadeInDown') . '" data-animation-delay="300">';
    echo '<a href="our-communities.php?newcommunity=' . $value['id'] . '"><img src="../images/communities/' . str_replace(" ", "-", strtolower($value['name'])) . '/' . $value['logo'] . '" width="150" /></a>';
    echo '<h4>' . $value['name'] . '</h4>';

    echo '<span><strong>Location: </strong>' . $value['locationLabel'] . '</span>';
    echo '<span><strong>Starting At: </strong>$' . number_format($value['min_home_price']) . '</span>';

    echo '</div>';
    if ($counter % 3 == 0) {
        echo '</div>';
    }
    $counter++;
}
?>