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

前端 未结 5 2113
醉话见心
醉话见心 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条回答
  •  旧时难觅i
    2020-12-11 07:45

    One solution is to cut the array into chunks, representing the columns, and then print the values in row order:

    $cols = array_chunk($arr, ceil(count($arr)/3));
    for ($i=0, $n=count($cols[0]); $i<$n; $i++) {
        echo $cols[0][$i];
        if (isset($cols[1][$i])) echo $cols[1][$i];
        if (isset($cols[2][$i])) echo $cols[2][$i];
    }
    

    If you don’t want to split your array, you can also do it directly:

    for ($c=0, $n=count($arr), $m=ceil($n/3); $c<$m; $c++) {
        echo $arr[$c];
        for ($r=$m; $r<$n; $r+=$m) {
            echo $arr[$c+$r];
        }
    }
    

提交回复
热议问题