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

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

    You can do a loop that will automatically insert a new line on each three elements:

    $values = array(1,1,1,1,1);
    
    foreach($values as $i => $value) {
      printf('%-4d', $value);
    
      if($i % 3 === 2) echo "\n";
    }
    

    EDIT: Since you added more information, here's what you want:

    $values = array(1,2,3,4,5);
    
    for($line = 0; $line < 2; $line++) {
      if($line !== 0) echo "\n";
    
      for($i = $line; $i < count($values); $i+=2) {
        printf('%-4d', $values[$i]);
      }
    }
    

    And if you want to bundle all that in a function:

    function print_values_table($array, $lines = 3, $format = "%-4d") {
      $values = array_values($array);
      $count = count($values);
    
      for($line = 0; $line < $lines; $line++) {
        if($line !== 0) echo "\n";
    
        for($i = $line; $i < $count; $i += $lines) {
          printf($format, $values[$i]);
        }
      }
    }
    

    EDIT 2: Here is a modified version which will limit the numbers of columns to 3.

    function print_values_table($array, $maxCols = 3, $format = "%-4d") {
      $values = array_values($array);
      $count = count($values);
      $lines = ceil($count / $maxCols);
    
      for($line = 0; $line < $lines; $line++) {
        if($line !== 0) echo "\n";
    
        for($i = $line; $i < $count; $i += $lines) {
          printf($format, $values[$i]);
        }
      }
    }
    

    So, the following:

    $values = range(1,25);
    print_array_table($values);
    

    Will output this:

    1   10  19  
    2   11  20  
    3   12  21  
    4   13  22  
    5   14  23  
    6   15  24  
    7   16  25  
    8   17  
    9   18  
    

提交回复
热议问题