[英]PHP complex while-loop logic
I'm having a problem writing a suitable while loop logic in php, here is my code: 我在用PHP编写适当的while循环逻辑时遇到问题,这是我的代码:
$applied_to = "Battery"; # rule applies to this product
$items = $_GET['items']; # how many items we have of this product
$forquan = 3; # rule applies to this quantity of product
$autoadd = "Power Inverter"; # when rule is met add this product.
if ($applied_to == "Battery"){
print "We Have $items $applied_to<br>";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br><hr />";
$counter = $items;
while($counter > 0){
if ($forquan / $items > 1){
print "we need 1 $autoadd<br>";
}
$counter--;
}
}
Now what i want is to add one additional product $autoadd
if we have 1-3 Batteries, and 2 $autoadd
if we have 3-6 and so on. 现在,我想要的是如果我们有1-3个电池,则添加一个附加产品
$autoadd
,如果我们有3-6个电池,则添加2个$autoadd
,依此类推。
I tried so many different combinations of while loops if statements etc, but i cant seem to get the perfect loop. 我尝试了多种多样的while循环if语句等组合,但是我似乎无法获得完美的循环。
<?php
$applied_to = "Battery"; # rule applies to this product
$items = $_GET['items']; # how many items we have of this product
$forquan = 3; # rule applies to this quantity of product
$autoadd = "Power Inverter"; # when rule is met add this product.
if ($applied_to == "Battery"){
print "We Have $items $applied_to<br>";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br><hr />";
while($items > 0){
echo abs($forquan/$items); #check abs value
if (abs($forquan/$items) > 1){
print "we need 1 $autoadd<br>";
}
$items--;
}
}
?>
You can simply calculate the number of required products and then iterate over that number: 您可以简单地计算所需产品的数量,然后遍历该数量:
<?php
$applied_to = "Battery"; # rule applies to this product
$items = $_GET['items']; # how many items we have of this product
$forquan = 3; # rule applies to this quantity of product
$autoadd = "Power Inverter"; # when rule is met add this product.
if ($applied_to == "Battery"){
print "We Have $items $applied_to<br>\n";
print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br>\n<hr />\n";
$countAddProducts = ceil($items / $forquan);
for ($i=0; $i<$countAddProducts; $i++) {
print "we need 1 $autoadd<br>\n";
}
}
The loops output then is n
times the string "we need 1 Power Inverter", where n
is the rounded up value of $items
divided by $forquan
. 然后,循环输出是字符串“我们需要1个功率逆变器”的
n
倍,其中n
是$items
的上舍入值除以$forquan
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.