【问题标题】:Nested Loop in table PHP表 PHP 中的嵌套循环
【发布时间】:2013-04-13 10:57:07
【问题描述】:

我是 PHP 新手,我正在尝试使用两个 foreach 制作一个表格,但没有得到我想要的输出。

<html>
    <head>
         <title>Didier Test</title>
    </head>
    <body>
        <h1>Yesso!</h1>
    </body>

    <table border="1">
        <tr>
            <th>Books</th>
            <th>Price</th>
        </tr>
    <tr>

    <?php foreach($name as $item): ?>
        <td><?=$item?></td>
        <?php foreach($price as $item2): ?>
            <td><?=$item2?></td>
            </tr>
        <?php endforeach; ?>
    <?php endforeach; ?>
    </table>

    </body>
</html>

我知道我的内部 foreach 有问题,但我不知道如何纠正它。

请告诉我。

【问题讨论】:

  • 哪个问题?怎么了?
  • 您的循环可能不起作用,因为您的变量中没有数据。请使用var_dump($name, $price) 并向我们展示结果。这些必须是数组才能使循环工作。

标签: php html foreach html-table


【解决方案1】:

首先,你在第 7 行关闭你的 body 标签,甚至在你输出你的表格之前。

<body>
<h1>Yesso!</h1>
</body>

我也不知道您为什么要对看似不相关的数据进行嵌套循环。除此之外,我们还需要查看您的查询。

【讨论】:

  • 可能所有商品的价格都相同,无论列是什么维度。但我怀疑 Zak 的回答是对的。
【解决方案2】:

由于您在第一个循环之前以&lt;tr&gt; 开始该行,因此您需要在该行之后以&lt;/tr&gt; 结束该行:

<tr>
<?php foreach($name as $item): ?>
<td><?=$item?></td>
    <?php foreach($price as $item2): ?>
<td><?=$item2?></td>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>

【讨论】:

    【解决方案3】:
    <?php 
    for($i = 0; $i< count($name); $i++) {
        $item  =  $name[$i];
        $item2 =  $price[$i];
    
    ?>
    <tr>
        <td><?=$item?></td>
        <td><?=$item2?></td>
    </tr>
    
    <?php 
    }
    ?>
    

    【讨论】:

      【解决方案4】:

      尝试用完整的&lt;?php echo 更改您的速记php 输出符号&lt;?=

      <html>
      <head>
        <title>Didier Test</title>
      </head>
      <body>
      <h1>Yesso!</h1>
      </body>
      <table border="1">
      <tr>
          <th>Books</th>
          <th>Price</th>
      </tr>
      <tr>
      <?php foreach($name as $item): ?>
          <td><?php echo $item?></td>
          <?php foreach($price as $item2): ?>
          <td><?php echo $item2?></td>
      </tr>
           <?php endforeach; ?>
      <?php endforeach; ?>
      </table>
      </body>
      </html>
      

      您可能没有得到任何输出,因为您的 php.ini 已设置为不允许速记 php '

      哦,是的,就像 Barmer 和 Revent 提到的那样,您也有一些 HTML 标记嵌套问题。欢迎来到 PHP 的美好世界,祝你好运:)

      【讨论】:

        猜你喜欢
        • 2012-08-11
        • 2012-09-17
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        相关资源
        最近更新 更多