【发布时间】:2023-03-17 07:05:02
【问题描述】:
为什么这个双 foreach 循环重复值
foreach($_POST['studentpoints'] as $value) {
foreach($_POST['studentids'] as $valor) {
$stmt->bindParam(':studentid', $studentids);
$stmt->bindParam(':studentpoints', $points);
$studentids = $valor;
$points = $value;
$stmt->execute();
}
此代码不重复值,而只读取学生的第一个 id
foreach($_POST['studentpoints'] as $value) {
foreach($_POST['studentids'] as $valor) {
$studentids = $valor;
}
$stmt->bindParam(':studentid', $studentids);
$stmt->bindParam(':studentpoints', $points);
$studentids = $valor;
$points = $value;
$stmt->execute();
}
数据库中的数据表
<?php foreach($rowstudents as $row): ?>
<tr>
<th><input type="hidden" name="studentids[]" value="<?php echo ' ' . htmlentities($row['studentid'], ENT_QUOTES, 'UTF-8') . ' ';?>" />
<?php echo '' . htmlentities($row['studentid'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><?php echo '' . htmlentities($row['fname'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><?php echo '' . htmlentities($row['lname'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><input type="text" name="studentpoints[]" value="<?php echo '' . htmlentities($row['studentpoints'], ENT_QUOTES, 'UTF-8') . '' ?>"></th>
</tr>
<?php endforeach; ?>
</table>
【问题讨论】:
-
这就是为什么你在调用双重 foreaches
-
这两个循环可以合二为一吗?
-
我可能会创建某种包含整行的
student对象。然后,您只需遍历学生并提取相关信息。除此之外,您需要一个for循环来获取索引——这需要更多的错误检查。为什么你不能只做$stmt->bindParam(':studentid', $valor);(虽然这不能解决你的重复问题)? -
@Clockwork-Muse 是的,我尝试过,但我仍然得到重复