在3列中显示1到10的数字

时间:2016-08-19 20:56:39

标签: php

我正在尝试在3列中显示1到10的数字。

我需要成为它:

1 5 8

2 6 9

3 7 10

4

下面是我的代码,但是它运行错误

$elems = 10;  

$array = array();
for ($q = 1; $q <= $elems; $q++)
    $array[] = $q;

$categories = $array;
$columns = 3;
$rows = 4;

echo '<table>';
for ($row = 0; $row < $rows; $row++) {
    echo '<tr>';
    foreach ($categories as $k => $category) {
        if ($k % $rows == $row) {
            echo '<td>' . $category . '</td>';
        }
    }

    echo '</tr>';
}

echo '</table>';

但我有:

1 5 9

2 6 10

3 7

4 8

1 个答案:

答案 0 :(得分:0)

首先,我会将您的算法重写为更快的算法:

$elems = 10;

$categories = range(1, $elems);
$columns = 3;
$rows = 4;

echo '<table>' . PHP_EOL;
for ($row = 0; $row < $rows; $row++) {
    echo '<tr>';
    for ($col = 0; $col < $columns; $col++) {
        echo '<td>' . @$categories[$rows * $col + $row] . '</td>';
    }

    echo '</tr>' . PHP_EOL;
}

echo '</table>';

,你需要计算每列中的元素,如下所示:

$elems_in_col = array();
$elem_left = $elems;
for ($col = 0; $col < $columns; $col++) {
    if ($elem_left % ($columns - $col) == 0) {
        $elems_in_col[$col] = $elem_left / ($columns - $col);
    } else {
        $elems_in_col[$col] = ceil($elem_left / ($columns - $col));
    }
    $elem_left -= $elems_in_col[$col];
}
var_export($elems_in_col);

这将给我们:

array (
  0 => 4,
  1 => 3,
  2 => 3,
)

并改变我们的输出逻辑。完整的结果将是:

$elems = 10;

$categories = range(1, $elems);
$columns = 3;
$rows = 4;

$elems_in_col = array();
$elem_left = $elems;
for ($col = 0; $col < $columns; $col++) {
    if ($elem_left % ($columns - $col) == 0) {
        $elems_in_col[$col] = $elem_left / ($columns - $col);
    } else {
        $elems_in_col[$col] = ceil($elem_left / ($columns - $col));
    }
    $elem_left -= $elems_in_col[$col];
}

echo '<table>' . PHP_EOL;
for ($row = 0; $row < $rows; $row++) {
    echo '<tr>';
    for ($col = 0; $col < $columns; $col++) {
        if ($elems_in_col[$col] < $row + 1) {
            echo '<td>&nbsp;</td>';
            continue;
        }
        $idx = 0;
        for ($i = $col - 1; $i >= 0; $i--) {
            $idx += $elems_in_col[$i];
        }
        $idx += $row;
        echo '<td>' . @$categories[$idx] . '</td>';
    }

    echo '</tr>' . PHP_EOL;
}
echo '</table>';