I want to split an array into rows as evenly as possible, obeying a minimum count per row constraint so that row counts are as close as possible to the minimum and the difference between different row counts is never more than 1.
In other words, the number of elements in each row can’t be lower than $min or higher than (2 * $min – 1).
For example, I have a 65-element array and a minimum row size constraint of 9.
$x = range(1, 65);
$min = 9;
I want to split the array into rows with longer rows occurring before shorter rows.
[
[ 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, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38],
[39, 40, 41, 42, 43, 44, 45, 46, 47],
[48, 49, 50, 51, 52, 53, 54, 55, 56],
[57, 58, 59, 60, 61, 62, 63, 64, 65],
]
2
Answers
I found the answer after hours of experimenting :D
By performing the following calculations, an approach using
array_splice()
andarray_chunk()
can replace iterated processes.$count
)$maxRows
)$maxRows
with the dividend rounded up ($maxColumns
)$maxRows
Code: (Demo)
The two chunking attempts (either of which might produce an empty array) are merge together by unpacking their rows using spread operators (
...
) inside of an array. If preferred,array_merge()
can be called instead of unpacking into an array.