dongque3797 2017-10-11 07:57
浏览 18
已采纳

打印乘法表的垂直和水平标题

I have two arrays:

$array1 = array(1,2,3,4,7,6);
$array2 = array(2,3,1,0,5);

Then I tried to create printTable function to print multiplication table for arrays:

function printTable($array1, $array2) {
  echo "<table border=1px>";
  foreach ($array2 as $vert_head) {
    echo "<tr>";
    foreach ($array1 as $hor_head) {
      echo "<td>". ($vert_head * $hor_head) ."</td>";
    }
    echo "</tr>";
  }
  echo "</table>";
}

And then print table:

$data = printTable($array1, $array2);

It works fine table is print. But how can I add horizontal and vertical header from arrays?

That how my table looks right now(just answers):

2 |  4 |  6 |  8 | 14 | 12 |
3 |  6 |  9 | 12 | 21 | 18 |
1 |  2 |  3 |  4 |  7 |  6 | 
0 |  0 |  0 |  0 |  0 |  0 |
5 | 10 | 15 | 20 | 35 | 30 |

How can I add headers:

|   | 1 |  2 |  3 |  4 |  7 |  6 |  
+---+---+----+----+----+----+----+
| 2 | 2 |  4 |  6 |  8 | 14 | 12 |
| 3 | 3 |  6 |  9 | 12 | 21 | 18 |
| 1 | 1 |  2 |  3 |  4 |  7 |  6 | 
| 0 | 0 |  0 |  0 |  0 |  0 |  0 |
| 5 | 5 | 10 | 15 | 20 | 35 | 30 |
  • 写回答

3条回答 默认 最新

  • du9698 2017-10-11 08:05
    关注

    I've included comments in place of modified code. It use and extra foreach loop to print heading.

    <?php
    
    $array1 = array(1,2,3,4,7,6);
    $array2 = array(2,3,1,0,5);
    
    function printTable($array1, $array2) {
      echo "<table border=1px>";
    
      /* In our table first cell is empty. So put a blank cell here. */
      echo '<tr><td></td>' ;
    
      /* Then print all headers in following cells */
      foreach($array1 as $head) {
        echo '<th>' . $head . '</th>' ;
      }
      /* close the first row */
      echo '</tr>';
    
      foreach ($array2 as $vert_head) {
        echo "<tr>";
    
        /* Before printing each row, print the left heading */
        echo '<td>' . $vert_head . '</td>' ;
    
        foreach ($array1 as $hor_head) {
          echo "<td>". ($vert_head * $hor_head) ."</td>";
        }
        echo "</tr>";
      }
      echo "</table>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示