2016-10-24 7 views
0

私はPHPで、適切なwhileループロジックを書いて、問題を抱えているが、ここに私のコードは次のとおりです。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--; 
    } 
} 

今私が望むものを私たちは持っている場合は、1つの追加の製品$autoaddを追加することです1〜3個の電池、2個の電池がある場合は$autoaddとなります。

私は非常に多くの異なるwhileループwhile文の組み合わせを試しましたが、完全なループを得ることはできません。

答えて

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>\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"; 
    } 
} 

ループの出力は、その後、我々は1電源インバータを必要とするn倍の文字列」であります"nは、$itemsを切り上げた値を、$forquanで割ったものです。

0

php5 Math function

<?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--; 
    } 
} 
?>