Jump to content

Create html structure in foreach loop


ttmt_73

Recommended Posts

I need to create structure like this

 



<div class="row">
<div class="col-sm-3">
<!--content loop 1-->
</div>
<div class="col-sm-3">
<!--content loop 1-->
</div>
<div class="col-sm-3">
<!--content loop 2-->
</div>
<div class="col-sm-3">
<!--content loop 2-->
</div>
</div>


<div class="row">
<div class="col-sm-3">
<!--content loop 3-->
</div>
<div class="col-sm-3">
<!--content loop 3-->
</div>
<div class="col-sm-3">
<!--content loop 4-->
</div>
<div class="col-sm-3">
<!--content loop 4-->
</div>
</div>


 

I need to create it in a single foreach loop but on each loop I only create this structure.

 



<div class="col-sm-3">
<!--content loop 1-->
</div>
<div class="col-sm-3">
<!--content loop 1-->
</div>


I thought I had it working with this. But this seems to skip the 3rd element in the array.

 



<div class="row">
     <?php
         $i = 0;
         foreach(....../*your code*/){
           if($i == 2){
               $i = 0;
               ?>
                  </div><div class="row">
               <?php
            } else {
                ?>
                 <div class="col-sm-3">
                     <!--content-->
                 </div>
               <?php
                $i++;
            }
         }
        ?>
</div>


 

I have a demo here to illustrate - http://viper-7.com/EsGoc9

Link to comment
https://forums.phpfreaks.com/topic/296867-create-html-structure-in-foreach-loop/
Share on other sites

What are the various "content loop" numbers?

 

Sounds like you basically just want a four-column layout, except using Bootstrap tables instead of actual tables. (Speaking of, are you sure you should not be using an actual table?)

column = 1
loop {
	if column = 1 then output column start
	output cell
	column = column % 4 + 1
	if column = 1 then output column end
}

// normally you would close out incomplete rows here
// no need with bootstrap

if column != 1 then output column end
$column = 1;
foreach (/* whatever */) {
	if ($column == 1) {
		echo "<div class='row'>";
	}

	echo "<div class='col-sm-3'>";
	// whatever
	echo "</div>";

	$column = ($column % 4) + 1;
	if ($column == 1) {
		echo "</div>";
	}
}

if ($column != 1) {
	echo "</div>";
}
But maybe I didn't understand your question. Maybe you want to use two loops at once?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.