我有一个名为example的mysql表。
Id | Amount | Left | Filled
1 | 1 | 1 | 0
2 | 4 | 4 | 0
5 | 7 | 7 | 0我有一个名为$var = 9的变量,现在我有一个名为$array的数组,其is为array([0] => 1, [1] => 2, [2] => 5),它本身就是一个mysql结果。如何创建一个循环,使数组中的is不断减去左边的值,并按照$var的总值继续填充,从而使表中的最终结果为
Id | Amount | Left | Filled
1 | 1 | 0 | 1
2 | 4 | 0 | 4
5 | 7 | 3 | 4发布于 2018-11-06 00:11:57
您可以使用while循环来循环ids并减少每次迭代中的数量。
我不确定你是如何访问你的数据库的,所以我把它留作伪的。
考虑以下代码:
$ids = array(1,2,5);
$value = 9;
function reduceAmount($id, $value) {
$query = mysqli_query($conn, "SELECT * FROM example WHERE Id='$id'");
$row = mysqli_fetch_array($query);
$take = min($row['Left'], $value); // the amount you can take (not more then what left)
$left = $row['Left'] - $take;
$filled = $row['Filled'] + $take;
$conn->query("UPDATE example SET Left='$left', Filled='$filled' WHERE Id='$id'")
return max(0, $value - $take);
}
while ($value > 0 && !empty($ids)) { // check if value still high and the options ids not finish
$id = array_shift($ids); //get first ID
$value = reduceAmount($id, $value);
}您可以在循环结束时检查value是否仍然大于0-当ids中没有足够的“数量”时,可能会发生这种情况
https://stackoverflow.com/questions/53157749
复制相似问题