Php代码不能完成

时间:2014-05-11 04:30:22

标签: php

我有一个代码:

    if($building->type_id==39)
 {
    if($building->level<5){
    $cost_time = 43200;
        }else{
    if($building->level>=5){
    $cost_time =32400;
        }else{
    if($building->level>=10){
    $cost_time =21600;
        }else{
    if($building->level>=15){
    $cost_time =10800;      
                }
            }
        }
    }
 }

前2个如果有效,第三个不起作用,它会显示在这种情况下如果时间32400(9小时)为什么显示第二个?

3 个答案:

答案 0 :(得分:2)

您应该指定条件,因为如果值$building->level等于11,那么两个条件 $building->level>=5$building->level>=10为真(但第二个条件甚至未经评估),但$building->level>=5条件优先,因此$cost_time被分配给32400 }。

if($building->type_id==39) {
   if($building->level<5){
      $cost_time = 43200;
   }else{
      if($building->level>=5 && $building->level < 10){
        $cost_time = 32400;
      }else{
        if($building->level>=10 && $building->level < 15){
          $cost_time = 21600;
      }else{
        if($building->level>=15){
          $cost_time = 10800;      
        }
      }
    }
  }
}

P.S。 :您可以使用更短的版本:

 if($building->type_id==39) {
   if($building->level<5){
      $cost_time = 43200;
   }else if ($building->level>=5 && $building->level < 10){
      $cost_time =32400;
   }else if ($building->level>=10 && $building->level < 15){
      $cost_time = 21600;
   } else if ($building->level>=15) {
      $cost_time = 10800;      
   }
 }

答案 1 :(得分:0)

if($building->type_id==39)
{
if($building->level<5)
{
$cost_time = 43200;
}
elseif($building->level>=5)
{
$cost_time =32400;
}
elseif($building->level>=10)
{
    $cost_time =21600;
}
else($building->level>=15)
{
$cost_time =10800;      
}

}

答案 2 :(得分:0)

这非常难以阅读......为了清晰起见,我建议改变它的编写方式。 这是失败的,因为condition >= 5在检查>= 10是否尝试这种方式之前是否满意......

$cost_time = 43200;
if($building->level>=5)
    $cost_time =32400; 
if($building->level>=10)
    $cost_time =21600;
if($building->level>=15)
    $cost_time =10800; 

这种方式$cost_time默认为43200,如果没有条件,则继续检查其他条件。