I'm trying to break a PHP array of 9 array items into 3 divs. My array is displayed as:
$array = array("item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9")
This might be a previously asked question but I couldn't find a working solution. I tried what I saw on a similar question here on Break PHP array into 3 columns but it didn't achieve it as I wanted.
The snippet of what I want to achieve is below...
.wrapper {
display: flex;
flex-direction: colum;
gap: 80px;
}
.wrapper div {
display: flex;
flex-direction: column;
}
<div >
<div>
<p>Item 1</p>
<p>Item 4</p>
<p>Item 7</p>
</div>
<div>
<p>Item 2</p>
<p>Item 5</p>
<p>Item 8</p>
</div>
<div>
<p>Item 3</p>
<p>Item 6</p>
<p>Item 9</p>
</div>
</div>
CodePudding user response:
If I understood you correctly, maybe this solution will work for you:
<?php
$data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9'];
$columnLimit = 3;
$columns = array_fill(0, $columnLimit, []);
foreach ($data as $key => $value) {
$columns[$key % $columnLimit][] = $value;
};
?>
<div >
<?php foreach ($columns as $column): ?>
<div>
<?php foreach($column as $item): ?>
<p><?=$item?></p>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
A working example can be seen here: https://onlinephp.io/c/bd015