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

前端 未结 5 2101
醉话见心
醉话见心 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:57

    $a = array(1,2,3,4,5);
    "{$a[0]} {$a[1]} {$a[2]}\n{$a[3]} {$a[4]}";
    

    or

    $a = array(1,2,3,4,5);
    "{$a[0]} {$a[1]} {$a[2]}".PHP_EOL."{$a[3]} {$a[4]}";
    

    or

    $a = array(1,2,3,4,5);
    $second_row_start = 3; // change to vary length of rows
    foreach( $a as $index => $value) {
      if($index == $second_row_start) echo PHP_EOL;
      echo "$value ";
    }
    

    or, perhaps if you want a longer array split into columns of 3?

    $a = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
    $row_length = 3; // change to vary length of rows
    foreach( $a as $index => $value) {
      if($index%$row_length == 0) echo PHP_EOL;
      echo "$value ";
    } 
    

    which gives

    1 2 3 
    4 5 6 
    7 8 9 
    10 11 12 
    13
    

提交回复
热议问题