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

时间:2017-10-11 07:57:15

标签: php

我有两个数组:

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

然后我尝试创建printTable函数来打印数组的乘法表:

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

然后打印表:

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

它工作正常表是打印。但是如何从数组添加水平和垂直标题?

我的表现在看起来如何(只是答案):

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 |

如何添加标题:

|   | 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 个答案:

答案 0 :(得分:2)

尝试以下方法:

<?php
$array1 = array(1,2,3,4,7,6);
$array2 = array(2,3,1,0,5);
function printTable($array1, $array2) {
  echo "<table border=1px>";
  echo "<thead><tr><td></td>";
  echo "<th>" . implode("</th><th>", $array1) . "</th>";
  echo "</tr></thead><tbody>";
  foreach ($array2 as $vert_head) {
    echo "<tr>";
    foreach ($array1 as $hor_head) {
      echo "<td>". ($vert_head * $hor_head) ."</td>";
    }
    echo "</tr>";
  }
  echo "</tbody></table>";
}

printTable($array1, $array2);

它使用implode()$array1转换为表格标题

答案 1 :(得分:1)

您也可以尝试使用这种方式。这是使用当前代码的最简单方法

$array1 = array(1,2,3,4,7,6);
$array2 = array(2,3,1,0,5);
function printTable($array1, $array2) {
  echo "<table border='1px' style='text-align:right'>";
  echo '<tr><td></td>' ;
  foreach($array1 as $head) {
    echo '<td>' . $head . '</td>' ;
  }
  echo '</tr>';
  foreach ($array2 as $vert_head) {
    echo "<tr>";
     echo '<td>' . $vert_head . '</td>' ;
    foreach ($array1 as $hor_head) {
      echo "<td>". ($vert_head * $hor_head) ."</td>";
    }
    echo "</tr>";
  }
  echo "</table>";
}
$data = printTable($array1, $array2);

答案 2 :(得分:0)

我已经在评论代码中添加了评论。它使用额外的foreach循环来打印标题。

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