我有一个给出这个数组的查询,
Array (
[0] => Array (
[id] => 1
[name] => name1
)
[1] => Array (
[id] => 2
[name] => name2
)
[2] => Array (
[id] => 3
[name] => name3
)
)
当返回到 HTML 页面并生成 foreach 时,它将表格复制为 3 个表格。
<?php foreach ($types AS $row_types) { ?>
<table class="table_style1">
<tr>
<th>Title</th>
<th>Title2</th>
</tr>
<tr>
<td><?php $row_types['name'][0]?></td>
<td>data 1</td>
</tr>
<tr>
<td><?php $row_types['name'][1]?></td>
<td>data 2</td>
</tr>
<tr>
<td><?php $row_types['name'][2]?></td>
<td>data 3</td>
</tr>
</table>
<?php } ?>
请帮我在这里只显示一张 table 。
最佳答案
问题是你不明白 foreach
作品。它获取您的数组并运行 foreach
中的代码数组中的每个条目一次。
用你的数组结构 foreach
将遍历数组的每个元素 $types
一次一个。作为 $types
中的元素是数组本身(即你有一个多维数组)$row_types
将是一个包含键 id
的数组和 name
.因为我们只需要一个表,每个数组一行,所以我们需要启动表,它的标题在 foreach
之外。循环。
<table class="table_style1">
<tr>
<th>Title</th>
<th>Title2</th>
</tr>
然后我们可以得到我们的foreach
为我们输出每一行
<?php foreach ( $types as $row_types ) { ?>
<tr>
<td><?= $row_types['id'] ?></td>
<td><?= $row_types['name'] ?></td>
</tr>
<?php } ?>
如果你注意到我正在使用 <?=
标签,这是 <?php echo
的快捷方式因为此时你并没有回显行中的内容,你只是放置了变量,什么也没做。
终于可以关表了
</table>
整个代码看起来像这样
<table class="table_style1">
<tr>
<th>Title</th>
<th>Title2</th>
</tr>
<?php foreach ( $types as $row_types ) { ?>
<tr>
<td><?= $row_types['id'] ?></td>
<td><?= $row_types['name'] ?></td>
</tr>
<?php } ?>
</table>
关于php - foreach 在 HTML 中创建重复表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015614/