Is there a way to create multiple rows of thirds using w3.css and a foreach loop also to populate the thirds with data from a sample database?
Tried using but this would create multiple thirds in a single row instead:
<?php foreach ($products as $index => $product) :?>
<div class="w3-row">
<?php foreach ($products as $index => $product) : ?>
<div class="w3-third w3-container">
<h2>product 1 </h2>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
Expected output:
<div class="w3-row">
<div class="w3-third w3-container">
<h2>Item 1 from a database</h2>
</div>
<div class="w3-third w3-container">
<h2>Item 2 from a database</h2>
</div>
<div class="w3-third w3-container">
<h2>Item 3 from a database</h2>
</div>
</div>
<div class="w3-row">
<div class="w3-third w3-container">
<h2>Item 4 from a database</h2>
</div>
<div class="w3-third w3-container">
<h2>Item 5 from a database</h2>
</div>
<div class="w3-third w3-container">
<h2>Item 6 from a database</h2>
</div>
</div>
CodePudding user response:
so you want to get a row for every third element of the loop. You can achieve this by checking how many of them should be in a row with modulo.
<?php foreach ($products as $index => $product): $aThird = ($index 1%3)===0; ?>
<?php if ($aThird): ?>
<div class="w3-row">
<?php endif ?>
<div class="w3-third w3-container">
<h2>product 1 </h2>
</div>
<?php if ($aThird): ?>
</div>
<?php endif ?>
</div>
<?php endforeach; ?>
But my I would strongly suggest to look at grid layout https://css-tricks.com/snippets/css/complete-guide-grid/
CodePudding user response:
You can use array_chunk() function. array_chunk() splits an array into chunks of new arrays
$myArray = ['Item-1','Item-2','Item-3','Item-4','Item-5','Item-6'];
$myArray = array_chunk($myArray, 3);
foreach($myArray as $Array){
echo '<div >';
foreach($Array as $Value){
echo '<div >'.$Value.'</div>';
}
echo '</div>';
}