skip to Main Content

I would like to loop foreach in php using twitter bootstrap where the result would be like this.
I have tried in many ways with modulus etc. can anybody help me?

    <div class="row">
        <div class="col-md-6">Item 1</div>
        <div class="col-md-6">Item 2</div>
    </div>
    <div class="row">
        <div class="col-md-4">Item 3</div>
        <div class="col-md-4">Item 4</div>
        <div class="col-md-4">Item 5</div>
    </div>
    <div class="row">
        <div class="col-md-6">Item 6</div>
        <div class="col-md-6">Item 7</div>
    </div>
    <div class="row">
         <div class="col-md-4">Item 8</div>
         <div class="col-md-4">Item 9</div>
         <div class="col-md-4">Item 10</div>
    </div>

and so on.
thanks in advance

  • I used the translator, sorry!

2

Answers


  1. $numRows = 4;
    $content = "";
    
    for ($i = 1; $i <= $numRows; $i++) {
        (($i % 2) == 0) ? $k = 2 : $k = 3;
    
        $content .= "<div class='row'>";
    
        for ($j = 1; $j <= $k; $j++) {
            $content .= "<div class='col-md" . ($k * 2) . "'>Item " . $j . "</div>";
        }
    
        $content .= "</div>";
    }
    
    echo $content;
    
    Login or Signup to reply.
  2. Assuming you’re outputting this from an array of data, here’s one way to do it:

    foreach (array_chunk($your_data, 5) as $row_set) {
        $first_row = array_splice($row_set, 0, 2); // iterate this and output as col-md-6
        $row_set;  //iterate what's left (if anything) and output as col-md-4
    }
    

    The exact way you output the HTML is up to you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search