I'm trying to break a PHP array into 3 columns (has to be columns, not rows) so it would look something like this:
Item 1 Item 2 Item 3
Item 4 Item 5 Item 6
Item 7 Item 8 Item 9
Item 10................
The best approach I can think of would be to break the main array into 3 arrays, 1 for each column although I can't work out the best approach to do this - more specifically the criteria I could use to generate the 3 arrays.
$data = array();
$columns = 3;
echo "<table><tr>";
for($i = 0; $i < count($data); $i++)
{
if($i%$columns == 0)
echo "</tr><tr>";
echo "<td>".$data[i$]."</td>";
}
echo "</tr></table>";
There you go, it just outputs another row when you get to your column count. You might need to add some logic when the data isnt a multiple of 3.
Using array_chunk you can split array :
$rows = array_chunk($yourArray, '3'); // 3 = column count;
foreach ($rows as $columns) {
echo "<div class='row'>";
foreach ($columns as $column) {
echo "<div class='column'>$column</div>";
}
echo "</div>";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With