对于循环 PHP 检查值并获取是否满足条件



我必须写一个php循环。如何最好地做。 Bsally 我有 3 条购买线。

  1. 数量 3
  2. 数量 4
  3. 数量 6

我总共需要 9 个数量。所以我必须遍历上面的每一行并获得 9 个数量.如何编写循环。是循环还是同时循环?

  1. 取第 1 行。 3 小于 9,所以取整 3。第 1 行变为 0 余额。
  2. 取第 2 行。 3+4=7 小于 9,所以取整 4。第 2 行变为 0 余额。
  3. 取第 3 行。 7+6 = 13 比 9 多。所以只拿需要的东西。即 9-7=2。7+(9-7( = 9。第 3 行变为 4 个单位余额。

我有蜜蜂尝试循环 if 条件。完全没有到达那里。

$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.

最新更新