Search code examples
phpfor-loopforeachtwitter-bootstrap-2col

How Can I fillup bootstrap grid using foreach?


As I am trying to make bootstrap grid structure using foreach two column and inside it's one row and two rows structure. Attached a screen shot for better to better view.

Note: Not issue with CSS but first three items are goes in grid as picture.

Counter is not taking col-md-4 and not sure where to use Counter increment counter++? What if I want to show first three items using foreach?

Any other way to workaround on this layout? Tried so far as below

  <?php $counter = 0;
            foreach($view->result as $result) {

      <div id="hot-post" class="row hot-post">      
            <?php if( $counter == 0 || $counter % 3 == 0 ) {    ?> 
            <div class="col-md-8 hot-post-left">
                <div class="post post-thumb">
                    // first element common body 

                </div>
            </div>

       <?php if( $counter == 1 || $counter == 2 ) { ?> 
          <div class="col-md-4 hot-post-right">
           <?php if( $counter == 1){ ?>
                <div class="post post-thumb">
                    // second element common body 
                 </div>

          </php if ( $counter == 2){
                <div class="post post-thumb">
                    // third element common body 
                 </div>
          </div>
         <?php counter++; } } ?>
       </div> //closing row 
      <?php } ?>  //closing foreach 

enter image description here


Solution

  • There are couple of syntax errors in your code, such as:

    • Opening and closing braces are not in sync i.e. foreach loop and if block(s) are not closed properly
    • counter++; should be $counter++;

    Plus, there are few logical errors as well. Change your code in the following way,

    <?php 
        $counter = 0;
        foreach($view->result as $result) { 
        ?>
            <div id="hot-post" class="row hot-post">      
            <?php if( $counter == 0 || $counter % 3 == 0 ) { ?> 
                <div class="col-md-8 hot-post-left">
                    <div class="post post-thumb">
                        // first element common body 
                    </div>
                </div>
            <?php } ?>
            <?php if( $counter != 0 && $counter % 3 != 0 ) { ?> 
                <div class="col-md-4 hot-post-right">
                <?php if( $counter % 3 == 1){ ?>
                    <div class="post post-thumb">
                        // second element common body 
                    </div>
                <?php } ?>
                <?php if ( $counter % 3 == 2){ ?>
                    <div class="post post-thumb">
                        // third element common body 
                    </div>
                </div>
                <?php } ?>
            </div>
        <?php
            }
            ++$counter;
        } 
    ?>