dongyi1748 2016-10-24 07:01
浏览 53
已采纳

PHP复杂的while循环逻辑

I'm having a problem writing a suitable while loop logic in php, here is my code:

$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.

I tried so many different combinations of while loops if statements etc, but i cant seem to get the perfect loop.

  • 写回答

2条回答 默认 最新

  • douguio0185 2016-10-24 07:19
    关注

    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>
    ";
        print "The rule says we need 1 $autoadd for each 1-$forquan $applied_to<br>
    <hr />
    ";
    
        $countAddProducts = ceil($items / $forquan);
        for ($i=0; $i<$countAddProducts; $i++) {
            print "we need 1 $autoadd<br>
    ";
        }
    }
    

    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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料