我必须编写一个php循环。最好怎么做。我基本上有3条购买线。
我总共需要9个数量。因此,我必须遍历以上每行并获得9数量。如何编写循环。是for循环还是while循环?
我有蜜蜂试图通过if条件进行循环。没到那里。
答案 0 :(得分:0)
$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.