在PHP中显示数组键和值的表

时间:2014-03-28 03:52:37

标签: php html arrays html-table

只是想知道有没有办法用数组键和值以表格格式显示数字索引数组?

我尝试执行以下代码,但它不起作用。

<body>
  <?php 
    $countries=array("United State","Canada","England","Russia","Japan");
  ?>
  <h2>Country List</h2>
  <?php 
    echo "<td>".(array_keys($countries,"United State"))."</td><td>".(array_values($countries))."</td>"; 
  ?>
</body>

1 个答案:

答案 0 :(得分:0)

您不需要任何阵列功能来实现此目的。只需foreach循环即可。这是一个带有表格样式的代码的改进版本:

<head>
    <style type="text/css">
        table {
            border-collapse: collapse;
            border: 1px solid black;
        }
        table td,th {
            border: 1px solid black;
        }
        td {
            text-align: center;
        }
    </style>
</head>

<body>

    <?php

    $countries = array(
        "United States",
        "Canada",
        "England",
        "Russia",
        "Japan"
    );

    ?>

    <h2>Country List</h2>

    <table>
        <th>SI No.</th>
        <th>Country Name</th>

        <?php

        foreach ($countries as $key => $value) {
            echo "<tr>";
            echo "<td>" . ++$key . "</td>\n<td>" . $value . "</td>";
            echo "</tr>";
        }

        ?>
    </table>
</body>

Working demo