I am going nuts here – hope you can help me figure this out! What is supposed to be very simple math is utterly confusing me.
$columns = 3;
$items = range(1,20);
$total = count($items);
$col1 = ???; $col2 = ???; $col3 = ???;
// $col1 must be an array of (1,2,3,4...)
// $col2 must be an array of (8,9,10,11...)
// $col3 must be an array of (15,16,17,18...)
COL1 COL2 COL3
1 8 15
2 9 16
3 10 17
4 11 18
5 12 19
6 13 20
7 14
The above is a visual example of what I am trying to achieve. Basically, for any given number of items in an array and for any given number of columns, how do I produce n number of arrays (equalling number of columns) that are as equal length as possible. If equal length is not possible (as in the example above), they must be spread out as evenly as possible and the last array must be the shortest.
Any guidance on how I construct $col1/2/3 in the example above would be much appreciated!
Please ignore the fact that I used range and integers to generate the array – this is just to simplify the example. Assume the array will contain strings.
Thanks for any help!
You do want to use
array_chunk, but you need to calculate the chunk size yourself: