I have a piece of code which reads an XML catalog file with SimpleXMLElement and prints out the containing products of that catalog into a css styled table on a website.
The code outputs every product next to each other. However I only want to show 4 products in a row.
I therefore need to insert some
<tr> </tr>
tags following every 4 (or x) number of products in the array.
How should I do this? My code is as follows:
echo '<table class="products">';
foreach (getProdutcsFromCatalog($grpName) as $product) {
$output = '
<td>
<h2>' .$product->title .'</h2>
<div class="img">
<img src="' .$product->img . '" height="150" width="100" class =""/>
</div>
<div>
'.$product->description.'
</div>
</div>
<div class="price">
<b>
'.$product->price . ' DKK' . '
</b>
</div>
<div class="addToCart">
<a href="#">Læg i kurv</a>
</div>
</td>
';
echo $output;
}
echo '</table>';
Initialise $i = 0;
before starting the foreach
loop. Then change your
echo $output;
}
to:
if( $i % 4 == 0 ) echo "<tr>";
echo $output;
if( $i % 4 == 3 ) echo "</tr>";
$i++;
}
If you only want 4 items per row I'd advise you to first loop through the XML structure and save all your items in an array, and then to array_chunk($items, 4)
the array and then loop through it and generate the table.