gpt4 book ai didi

php - 具有多对多关系的嵌套 foreach 循环

转载 作者:行者123 更新时间:2023-11-29 05:45:49 24 4
gpt4 key购买 nike

我使用名为 groupparty 的查找表在多对多关系中有两个表(组和方)。我希望能够为每一方分配价格,这样属于两个组的一方可能在一组中有一个价格,在另一组中有不同的价格。在表 groupparty 中,我有三列:groupid、partyid 和 totalprice。因此,要指定价格,我有以下形式:

<form action="" method="post">
<?php foreach ($groups as $group): ?>
<input type="hidden" name="groupids[]"
value="<?php echo $group['id']; ?>"/>
<?php htmlout($group['groupname']); ?>
<label for="totalprice">Price:
<input type="text" name="totalprices[]" id="totalprice"
value="<?php htmlout($totalprice); ?>"/></label><br />
<?php endforeach; ?>
<input type="hidden" name="id" value="<?php htmlout($id); ?>"/>
<input type="submit" name="action" value="Set"/>
</form>

在 mysql 方面,我已经达到了以下脚本。它几乎可以工作,只是它将在上面的表单中输入的最后一个 totalprice 值插入到所有关联的组中。任何其他 totalprice 值都将丢失 - 我只剩下一个分配值:

 if (isset($_POST['action']) and $_POST['action'] == 'Set')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);

foreach($_POST['groupids'] as $groupid)
foreach($_POST['totalprices'] as $totalprice)
{
$sql = "UPDATE groupparty SET
totalprice = '$totalprice'
WHERE groupid = '$groupid'
AND partyid = '$id'";
mysqli_query($link, $sql);
}
}

欢迎提出任何建议。谢谢。

最佳答案

您可以调整您的结构以使更新更容易——只需将组 ID 作为键传递给 HTML 中的 totalprices[] 数组:

<form action="" method="post">
<?php foreach ($groups as $group): ?>
<?php echo($group['groupname']); ?>
<label for="totalprice">Price:</label>
<input type="text" name="totalprices[<?php echo $group['id']; ?>]" id="totalprice" value="<?php echo($totalprice); ?>"/></label><br />
<?php endforeach; ?>
<input type="hidden" name="id" value="<?php htmlout($id); ?>"/>
<input type="submit" name="action" value="Set"/>
</form>

然后,您可以循环遍历该数组:

if (isset($_POST['action']) and $_POST['action'] == 'Set')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);

foreach($_POST['totalprices'] as $groupid => $totalprice)
{
// Remember to also escape these
$groupid = mysqli_real_escape_string($link, $groupid );
$totalprice = mysqli_real_escape_string($link, $totalprice);

$sql = "UPDATE
groupparty
SET
totalprice = '$totalprice'
WHERE
groupid = '$groupid'
AND
partyid = '$id'";

mysqli_query($link, $sql);
}
}

您当前结构的问题在于,对于每个组 ID,您循环遍历 所有 价格,因此很明显,当到达最后一次迭代时,最后一个值将覆盖前一个值。

鉴于您有第 1、2 和 3 组以及价格 20、25 和 30。您的循环当前循环遍历如下值:

Group   Price
1 20
1 25
1 30 # This is the last price Group 1 gets
2 20
2 25
2 30 # This is the last price Group 2 gets
3 20
3 25
3 30 # This is the last price Group 3 gets

当你真正想要这个的时候:

Group   Price
1 20 # This is the last price Group 1 gets
2 25 # This is the last price Group 2 gets
3 30 # This is the last price Group 3 gets

正如您从上表中看到的那样,所有组都获得价格 30,因为这是每个组获得的最后价格。

关于php - 具有多对多关系的嵌套 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2238613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com