在php中创建三角形模式表

时间:2017-01-07 02:25:12

标签: php

我在php中创建三角形模式表有问题,我写这样的代码,

echo "<table border ='1' cellpadding='10px' cellspacing='10px' style='border-collapse: collapse'>";  
    $rows = array('5', '3', '1', '3', '5');

    foreach($rows as $row){
        $rowArray = $row;
        echo "<tr>";
        $cols = array('1', '2', '3', '4', '5');
        for ($j=0; $j<$rowArray; $j++){
            $array[$j] = $cols[$j];
            echo "<td>". $array[$j] ."</td>";
        }
        echo "</tr>";  
    }
echo "</table><br>";

结果

---------------------
| 1 | 2 | 3 | 4 | 5 |
|--------------------
| 1 | 2 | 3 |   |   |
|--------------------
| 1 |   |   |   |   |
|--------------------
| 1 | 2 | 3 |   |   |
|--------------------
| 1 | 2 | 3 | 4 | 5 |
|--------------------

但我期待结果如下

---------------------
| 1 | 2 | 3 | 4 | 5 |
|--------------------
|   | 2 | 3 | 4 |   |
|--------------------
|   |   | 3 |   |   |
|--------------------
|   | 2 | 3 | 4 |   |
|--------------------
| 1 | 2 | 3 | 4 | 5 |
|--------------------

任何人都可以按照我的预期逐步解释创建结果吗?

1 个答案:

答案 0 :(得分:1)

也许你可以为这样的空列添加另一个数组。

$table = '<table border ="1" cellpadding="10px" cellspacing="10px" style="border-collapse: collapse">';
$rows = array('5', '3', '1', '3', '5');
//created an object array for how may empty columns should be added on both before and after the not empty columns base on the $rows array.
$emptyColObj = array(5=>0,3=>1,1=>2);
foreach($rows as $row){
    $rowArray = $row;
    echo $emptyRow;
    $table .= "<tr>";
    //create a loop to make an empty column
    //before not empty column
    for($e=0;$e<$emptyColObj[$rowArray];$e++){
        $table .= "<td></td>";
    }
    $cols = array('1', '2', '3', '4', '5');
    for ($j=0; $j<$rowArray; $j++){
        $array[$j] = $cols[$j];
        $table .= "<td>". $array[$j] ."</td>";
    }
    //create a loop to make an empty column
    //after not empty column
    for($e=0;$e<$emptyColObj[$rowArray];$e++){
        $table .= "<td></td>";
    }
    $table .= "</tr>";  
}
$table .= '</table>';
echo $table;

输出:

---------------------
| 1 | 2 | 3 | 4 | 5 |
|--------------------
|   | 2 | 3 | 4 |   |
|--------------------
|   |   | 3 |   |   |
|--------------------
|   | 2 | 3 | 4 |   |
|--------------------
| 1 | 2 | 3 | 4 | 5 |
|--------------------