How do I distribute values of an array in three columns?

前端 未结 5 2103
醉话见心
醉话见心 2020-12-11 06:56

I need this output..

1 3 5
2 4 6

I want to use array function like array(1,2,3,4,5,6). If I edit this array like array(1

5条回答
  •  独厮守ぢ
    2020-12-11 07:33

    Here's something I whipped up. I'm pretty sure this could be more easily accomplished if you were using HTML lists, I've assumed you can't use them.

    $arr    = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16);
    $max    = count($arr);
    $cols   = 3;
    $block  = ceil($max / $cols);
    for ($i = 0; $i < $block ; $i++) {
        echo $arr[$i] . ' ';
    
        for ($j = 1; $j < $cols; $j++) {
            $nexKey = $i  + $block * $j;
            if (!isset($arr[$nexKey])) break;   
            echo $arr[$nexKey] . ' ';
        }
        echo '
    '; }

    NOTE : You can easily refactor the code inside the loop that uses $nexkey variable by making it into a loop itself so that it works for any number of columns. I've hardcoded it.

    Uses loops now.

提交回复
热议问题