I've been trying to figure out how to take an array of items and divide it into 4 html lists (that's my specific need but divide by X would be better), with the extra requirement that any remainders be added from the front.
This is different to array_chunk()
which will do the following:
item 1 item 4 item 7 item10
item 2 item 5 item 8
item 3 item 6 item 9
Where in fact what I need is this:
item 1 item 4 item 7 item 9
item 2 item 5 item 8 item 10
item 3 item 6
With array_chunk()
I can get the first output with something like this answer but array_chunk()
takes a number of items per chunk as an argument and just leaves the last chunk shorter than the rest.
<?php
$item_arr = array(1,2,3,4,5,6,7,8,9,10);
$col_cnt = 4;
$item_cnt = count($item_arr);
$row_cnt = ceil($item_cnt/$col_cnt);
$item_in_last_row = $item_cnt%$col_cnt;
$temp_cnt = $row_cnt-1;
$curr_cnt = $row_cnt;
$curr_item = 0;
for($i=0;$i<$row_cnt;$i++){
$curr_cnt = $row_cnt;
for($j=$i,$x=0,$k=1;$x<$col_cnt;$x++,$j+=$curr_cnt){
if($curr_item == $item_cnt){
break;
}
if($k > $item_in_last_row && $item_in_last_row != 0){
$abc = $curr_cnt;
$curr_cnt = $temp_cnt;
$temp_cnt = $abc;
}
print $item_arr[$j]." ";
$k++;
$curr_item++;
}
print "<br>";
}
?>
Output:
1 4 7 9
2 5 8 10
3 6