我在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--;
}
}
现在我想要的是添加一个额外的产品$autoadd
如果我们有1-3个电池,2个$autoadd
如果我们有3-6等等。
我尝试了很多不同的while循环if语句等组合,但我似乎无法获得完美的循环。
答案 0 :(得分:0)
<?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--;
}
}
?>
答案 1 :(得分:0)
您可以简单地计算所需产品的数量,然后迭代该数字:
hash[magazine[i]]++;
然后循环输出是<?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";
}
}
次字符串&#34;我们需要1个电源逆变器&#34;,其中n
是n
的向上舍入值除以{{ 1}}。