表PHP中的嵌套循环

时间:2013-04-19 23:36:26

标签: php html foreach html-table

我是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>

我知道我的内心有一个问题,但我不知道如何纠正它。

请告诉我。

4 个答案:

答案 0 :(得分:0)

有一件事你甚至在输出你的桌子之前就在第7行关闭了你的身体标签。

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

我也不知道你为什么要在看似不相关的数据上做嵌套循环。除此之外,我们需要查看您的查询。

答案 1 :(得分:0)

由于您在第一个循环之前使用<tr>开始行,因此您需要在其后面加</tr>行:

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

答案 2 :(得分:0)

<?php 
for($i = 0; $i< count($name); $i++) {
    $item  =  $name[$i];
    $item2 =  $price[$i];

?>
<tr>
    <td><?=$item?></td>
    <td><?=$item2?></td>
</tr>

<?php 
}
?>

答案 3 :(得分:0)

尝试使用完整<?=

更改速记php输出表示法<?php echo
<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&amp;的精彩世界祝你好运:)

相关问题