【问题标题】:how do I put loop into html table?如何将循环放入 html 表中?
【发布时间】:2011-06-18 03:59:58
【问题描述】:

foreach($matches as $match){ echo match[1]."-".match[2];}

我希望match[1]match[2] 值应该显示在一个包含两列的html 表格中。例如

Name    |   Percent
--------|-----------
Mathew  |   95%

其中 mathew 是 match[1] 而 percent 是 match[2]

我如何在两者之间添加 html 标记,供您参考,大约有 50 个名称。

【问题讨论】:

  • 你的匹配数组不能做你想做的事情。你会从数据库中提取它们吗?

标签: php html loops for-loop


【解决方案1】:

你的匹配数组不能做你想做的事情。我猜你是从数据库中提取数据。

<?php
$query = "SELECT * FROM `db_table` ";
$result= mysql_result($query);
?>
<table>
while($matches = mysql_fetch_assoc($result)){
?>
      <tr>
        <?php
        foreach($matches AS $match) {
        ?>
        <td><?php echo $match[0]; ?></td>
        <td><?php echo $match[1]; ?></td>        
        <?php
        }
        ?>
      </tr>

<?php
}
?>   
</table>

【讨论】:

    【解决方案2】:
    <table>
    <tr>
      <th>Name</th>
      <th>Percent</th>
    </tr>
    <?php foreach($matches as $match): ?>
      <tr>
        <td><?php print $match[1]; ?></td>
        <td><?php print $match[2]; ?></td>
      </tr>
    <?php endforeach; ?>
    </table>
    

    请注意,您的真正意思是 match[1] 和 match[2],而不是 match[0] 和 match[1]... PHP 数组中的第一个元素是 0。

    【讨论】:

    • 如果 $matches 来自 preg_match_all(..., ..., $matches, PREG_SET_ORDER),则子组索引以 1 开头。:)
    【解决方案3】:
    <table>
    <?php
    foreach($matches as $match) {
    ?>
    <tr><td><?php echo $match[1]; ?></td>
        <td><?php echo $match[2]; ?></td>
    </tr>
    <?php
    }
    ?>
    </table>
    

    【讨论】:

    • 但这是一个循环,所以行数更多
    • 除了忘记表头之外,我看不出有什么问题...他们正在循环打印行...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多