Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何减少嵌套if-else条件?_Php_If Statement_Nested_Reduce - Fatal编程技术网

Php 如何减少嵌套if-else条件?

Php 如何减少嵌套if-else条件?,php,if-statement,nested,reduce,Php,If Statement,Nested,Reduce,我在代码中嵌套了很多if-else条件。我做了34次。你知道,这真的让我发疯。请告诉我如何减少它。多谢各位 这是我的代码: if ($input_age > $age_min && $input_age <$age_max){ if ($input_heigh > $heigh_min && $input_heigh < $heigh_max){ if ($input_ds == "yes" && $ds_val=

我在代码中嵌套了很多if-else条件。我做了34次。你知道,这真的让我发疯。请告诉我如何减少它。多谢各位

这是我的代码:

if ($input_age > $age_min && $input_age <$age_max){
 if ($input_heigh > $heigh_min && $input_heigh < $heigh_max){
    if ($input_ds == "yes" && $ds_val=="yes" ){ 
    //some calculation
    }
    else if ($input_ds == "no" && $ds_val=="yes"){ 
    //some calculation

    }
    else if ($input_ds == "yes" && $ds_val=="no"){ 
    //some calculation

    }
    else if ($input_ds == "no" && $ds_val=="no"){ 

    //some calculation  

    }
}
else if ($input_heigh < $heigh_min || $input_heigh > $heigh_max){
    if ($input_ds == "yes" && $ds_val=="yes" ){
    //some calculation

    }
    else if ($input_ds == "no" && $ds_val=="yes" ){ 
    //some calculation

    }

    else if ($input_ds == "yes" && $ds_val=="no"){ 
    //some calculation

    }
    else if ($input_ds == "no" && $ds_val=="no" ){ 
    //some calculation

    }
}
if($input\u age>$age\u min&&$input\u age$heigh\u min&&$input\u heigh<$heigh\u max){
如果($input_ds==“yes”&&$ds_val==“yes”){
//一些计算
}
如果($input_ds==“否”&&$ds_val==“是”){
//一些计算
}
如果($input_ds==“yes”&&$ds_val==“no”){
//一些计算
}
如果($input_ds==“no”&&$ds_val==“no”){
//一些计算
}
}
else if($input_heigh<$heigh_min | |$input_heigh>$heigh_max){
如果($input_-ds==“yes”&&$ds_-val==“yes”){
//一些计算
}
如果($input_ds==“否”&&$ds_val==“是”){
//一些计算
}
如果($input_ds==“yes”&&$ds_val==“no”){
//一些计算
}
如果($input_ds==“no”&&$ds_val==“no”){
//一些计算
}
}

如果还有更多的条件,我建议在这种情况下使用switch,因为它更容易阅读。下面是一个简单的例子:

switch($input_ds.$ds_val){
   case 'yesyes':
      //some calculations
      break;
   case 'yesno':
      //some calculations
      break;
   case 'noyes':
      //some calculations
      break;
   case 'nono':
      //some calculations
      break;
}

这是你不喜欢的嵌套布局吗?因为你可以把代码重构成函数来处理每次计算,使代码更容易阅读。@gunnx-你明白我的意思了吗?我正要写一些类似的东西…很高兴我读到了这篇文章,我不知道你能用这样的开关。谢谢你的发帖。谢谢你,但它仍然使用如果其他条件,仪式?我猜它不会减少elseif条件,它会减少elseif条件,在本例中,从代码的第一个if块开始切换reduce all elseif cond