0

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.

Community
  • 1
  • 1
GusRuss89
  • 1,314
  • 2
  • 13
  • 20
  • Possible duplicate of [Split array into a specific number of chuncks](http://stackoverflow.com/questions/15723059/split-array-into-a-specific-number-of-chuncks), not sure, but I think it will help you?! – Naruto Dec 02 '15 at 08:35
  • What if you have 9 or 11 elements instead of 10? Use loop and count reminder, do some algorithm for that. – Justinas Dec 02 '15 at 08:38
  • The answer lies in [this answer to a similar question](http://stackoverflow.com/a/15723262/1466282). Thank you everyone for the responses. – GusRuss89 Dec 03 '15 at 01:52

1 Answers1

1
<?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
harry
  • 1,007
  • 2
  • 10
  • 19