在foreach循环中创建一个表,然后使用php为数组的每个项打印相同的html元素(输入)(只使用一次循环)
这是我非常草率的代码:在foreach循环中创建一个表,然后使用php为数组的每个项打印相同的html元素(输入)(只使用一次循环),php,arrays,loops,foreach,html-table,Php,Arrays,Loops,Foreach,Html Table,这是我非常草率的代码: <?php $data = $_POST['fullName']; $first = $names[0]; include('header.php'); ?> <form action="other-page.php" method="post" enctype="multipart/form-data"> <div class="users"
<?php
$data = $_POST['fullName'];
$first = $names[0];
include('header.php');
?>
<form action="other-page.php" method="post" enctype="multipart/form-data">
<div class="users">
<table>
<tr>
<?php
foreach ($data as $key => $singledata) {
echo "<th>$singledata</th>";
}
?>
</tr>
<tr>
<?php
foreach ($data as $key => $singledata) :
?>
<td><input type="checkbox" name="myvalue<?= $key ?>" value="myvalue<?= $key ?>" checked></td>
<?php
endforeach;
?>
</tr>
<tr>
<?php
foreach ($data as $key => $singledata) :
?>
<td><input type="checkbox" name="myother value<?= $key ?>" value="myother value <?= $key ?>"></td>
<?php
endforeach;
?>
</tr>
</table>
</div>
</form>
<?php include('footer.php') ?>
这将创建一个可重用和循环的数组,但如果以后不在每次创建数组时循环使用它(我的第一种方法),那将是无用的
我可以创建一个变量并将其命名为$table,然后附加剩余的HTML:
$table = '<tr>';
foreach ($data as $key => $singledata) {
$table .= "<td>$key<td>";
}
$table .= '</tr>';
$table='';
foreach($key=>$singledata形式的数据){
$table.=“$key”;
}
$table.='';
但只要我将tr添加到循环中,它就会为数组的所有元素创建一个额外的标记
所以也不是很有用
我只想为几个用户名打印相同的输入,我很确定我遗漏了什么。您可以在外部循环中生成每一行的内容(如您在最后一段代码中所示),然后简单地将它们回显到表中:
<?php
$headers = '';
$myvalue_row = '';
$myothervalue_row = '';
foreach ($data as $key => $singledata) {
$headers .= "<th>$singledata</th>";
$myvalue_row .= "<td><input type=\"checkbox\" name=\"myvalue$key\" value=\"myvalue$key\" checked></td>";
$myothervalue_row .= "<td><input type=\"checkbox\" name=\"myothervalue$key\" value=\"myothervalue$key\" checked></td>";
}
?>
<form action="other-page.php" method="post" enctype="multipart/form-data">
<div class="users">
<table>
<tr><?= $headers ?></tr>
<tr><?= $myvalue_row ?></tr>
<tr><?= $myothervalue_row ?></tr>
</table>
</div>
</form>
1。现在将在循环中渲染的元素移动到三个不同的部分模板文件中。2.使用php ob_start()和ob_get_clean()函数将每行内容添加到一个循环中的三个不同变量中。3.在主模板中,只需回显其行元素中包含表行内容的每个变量。对于部分模板,您是什么意思?我的意思是,您可以将其移动到单独的文件中。第一个文件内容将是,即以下$singledata,然后将其“呈现”到变量,如下所示:
<?php
$headers = '';
$myvalue_row = '';
$myothervalue_row = '';
foreach ($data as $key => $singledata) {
$headers .= "<th>$singledata</th>";
$myvalue_row .= "<td><input type=\"checkbox\" name=\"myvalue$key\" value=\"myvalue$key\" checked></td>";
$myothervalue_row .= "<td><input type=\"checkbox\" name=\"myothervalue$key\" value=\"myothervalue$key\" checked></td>";
}
?>
<form action="other-page.php" method="post" enctype="multipart/form-data">
<div class="users">
<table>
<tr><?= $headers ?></tr>
<tr><?= $myvalue_row ?></tr>
<tr><?= $myothervalue_row ?></tr>
</table>
</div>
</form>