Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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,2,3), it means the output need to show like

1 2 3

The concept is maximum 3 column only. If we give array(1,2,3,4,5), it means the output should be

1 3 5 
2 4

Suppose we will give array(1,2,3,4,5,6,7,8,9), then it means output is

1 4 7
2 5 8
3 6 9

that is, maximum 3 column only. Depends upon the the given input, the rows will be created with 3 columns.

Is this possible with PHP? I am doing small Research & Development in array functions. I think this is possible. Will you help me?

For more info:
* input: array(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
* output:

1  6   11 
2  7   12 
3  8   13 
4  9   14 
5  10  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
298 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 "
";
}

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 "
";

  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 "
";

    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 "
";

    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  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...