【问题标题】:For loop PHP to check the value and take if condition is metFor循环PHP检查值并满足条件
【发布时间】:2019-09-08 09:19:26
【问题描述】:
我必须编写一个 php 循环。怎么做最好。基本上我有 3 条购买线。
- 数量 3
- 数量 4
- 数量 6
我总共需要 9 个。所以我必须遍历上面的每一行并得到 9 qty 。如何编写循环。是for循环还是while循环?
- 取第 1 行。3 小于 9,所以取整个 3。第 1 行变为 0 余额。
- 取第 2 行。3+4=7 小于 9,所以取整 4。第 2 行变为 0 余额。
- 取第 3 行。7+6 = 13 多于 9。所以只取所需的部分。即 9-7=2。 7+(9-7) = 9。第 3 行变为 4 个单位余额。
我一直在尝试使用 if 条件进行循环。完全没有到达那里。
【问题讨论】:
标签:
php
for-loop
while-loop
【解决方案1】:
$items = [3,4,6]; //can also be used as an associative array with "item1" => 3 likewise
$requiredQuantity = 9;
$currentQuantity = 0;
$i = 0; //incrementor
foreach ($items as $item){
if(($currentQuantity+$item) < $requiredQuantity){
$currentQuantity += $item;
$items[$i] = 0;
}
elseif(($currentQuantity+$item) == $requiredQuantity){
$currentQuantity += $item;
$items[$i] = 0;
break;
}
else{
$shortageQuantity = $requiredQuantity - $currentQuantity;
$items[$i] -= $shortageQuantity;
$currentQuantity += $shortageQuantity;
break;
}
$i++;
} //end of foreach loop
print_r($items); //resultant items list.