I have an interesting problem, seems like it would have been solved long ago but can't find anything.
I have a simple array, variable length.
I need to put the array in a table BUT only X columns wide. Meaning, if the array has 25 values, and I only want 3 columns, there will be 2 columns of 11 and 1 column of 3 (the remainder).
Like this (each number represents a value in a table cell):
1 12 23
2 13 24
3 14 25
4 15
5 16
6 17
7 18
8 19
9 20
10 21
11 22
I've spent all day afternoon this, seems like it would be simple, but either my game is off today or it's harder than I think.
Of course, no problem going horizontally, easy, but vertically is the requirement and I never know the size of the array and number of columns can vary.
Thanks for any help!
In the case you want the last column to have as many elements as posible to fit the other columns (the most dynamic case for this problem), this would be a solution:
<?php
$numberOfColumns = 3;
$myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];
$arrayLength = count($myArray); // 25
$columnLength = ceil($arrayLength / $numberOfColumns); // 9
for ($i = 0; $i < $columnLength; $i++) {
for ($j = 0; $j < $numberOfColumns; $j++) {
$arrayIndex = $j * $columnLength + $i;
if ($arrayIndex < $arrayLength) {
echo $myArray[$arrayIndex] . " ";
}
}
echo '<br>';
}
This is the output in my browser:
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