簡體   English   中英

PHP復雜的While循環邏輯

[英]PHP complex while-loop logic

我在用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-3個電池,則添加一個附加產品$autoadd ,如果我們有3-6個電池,則添加2個$autoadd ,依此類推。

我嘗試了多種多樣的while循環if語句等組合,但是我似乎無法獲得完美的循環。

php5數學函數

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

您可以簡單地計算所需產品的數量,然后遍歷該數量:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM