如何将数组的值分布在三列中? [英] How do I distribute values of an array in three columns?

查看:43
本文介绍了如何将数组的值分布在三列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这个输出..

1 3 5
2 4 6

我想使用像array(1,2,3,4,5,6)这样的数组函数.如果我像 array(1,2,3) 一样编辑这个数组,这意味着输出需要像

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

这个概念最多只有 3 列.如果我们给出array(1,2,3,4,5),则表示输出应该是

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

假设我们给array(1,2,3,4,5,6,7,8,9),则表示输出为

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

也就是说,最多只有 3 列.根据给定的输入,将创建 3 列的行.

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

这可以用 PHP 实现吗?我在做小型研究&数组函数的开发.我认为这是可能的.你会帮我吗?

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

欲了解更多信息:
* 输入:array(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
* 输出:

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  

推荐答案

你可以做一个循环,自动在每三个元素上插入一个新行:

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

由于您添加了更多信息,这就是您想要的:

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]);
    }
  }
}

编辑 2: 这是一个修改后的版本,它将列数限制为 3.

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]);
    }
  }
}

所以,以下:

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

将输出:

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  

这篇关于如何将数组的值分布在三列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆