开发者

Change for in PHP with table

<table><tr>
<?php
             for($i=0;$i<15;$i++) {

                if($i%5 == 0) {echo '</tr> <tr>开发者_StackOverflow;';}
                ?><td><?php echo $i ?></td> 

            <?php
            }?>
                </tr>
</table>

this generate:

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

how can I make:

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

?


You need a nested loop

<table>
    <?php
    $rows = 3;
    for($i=0 ; $i < $rows ; $i++ ) {
        echo "<tr>";
        for( $j = 0 ; $j < 5 ; $j++ ) { 
            echo "<td>" . ($j * $rows + $i) . "</td>";
        }
        echo "</tr>";
    }
    ?>
</table>


I tried to make the variable names descriptive:

<table>
<?php
// Set the number of rows, cols, and starting number here:
$number_rows = 3;
$number_cols = 5;
$starting_num = 0;

// You can use foreach w arrays... much easier
$rows    = range(0,$number_rows - 1);
$cols    = range(0,$number_cols - 1);

foreach($rows as $one_row) {
?>
    <tr>
    <?php
    foreach($cols as $one_col) {

        // Do the calculation
        echo "<td>" . 
             ($starting_num + $one_col + ( max($rows) * $one_col ) + $one_row) .
             "</td>";
    }
    ?>
    </tr>
<?php
}
?>
</table>

Working example like in the OP.

Now let's say you want to go from (1300-1431), then you start at 1300 and want a 4 x 8.

$number_rows  = 8;
$number_cols  = 4;
$starting_num = 1300;

Like this.

There are two "tricks."

The first is using range() to quickly define an array integers. I find arrays more pleasant to work with than raw numbers, since arrays can be worked on with the intuitive construct of foreach().

The second is figuring out how to know what number to print if you have the column, row, and starting, number. It's simplest to figure out the numbers for the first row and go from there. Let's number the rows and cols from 0. So col:0 row:0 will be the starting number. Col:1 Row:0, the number to the right, will just be the starting number + one (the column number) + the number of rows less one (easiest to see by looking at the matrix of number), and the number of rows less one is the maximum number in the rows array. So for the first row we have:

$starting_num + $one_col + ( max($rows) * $one_col )

then all we just add the row number to take that into account, and we've got it all:

$starting_num + $one_col + ( max($rows) * $one_col ) + $one_row


Tested example with given start and end:

<table>
<?php
$start = 1300;
$end = 1432;
$n = $end - $start + 1;
$cols = 5;
$rows = ceil($n / $cols);

for($i=0 ; $i < $rows ; $i++ ) {
    echo "<tr>";
    for( $j = 0 ; $j < $cols ; $j++ ) { 
        $val = $j * $rows + $i;
        echo "<td>";
        echo ($val < $n) ? $val + $start : '&nbsp;'; 
        echo "</td>";
    }
    echo "</tr>";
}
?>
</table>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜