避免在 PHP 中使用多个 if 语句(使用数组或其他选项)


Avoid multiple if statements in PHP (use array or some other option)

我正在使用PHP创建一个转换表,我必须根据很多场景检查用户的输入,我开始使用if语句,但这似乎没有任何效率,我希望有一种更简单的方法来完成所有场景。

我研究了三元和切换选项,但这些选项似乎没有做我需要它做的事情,我还考虑了数组(我认为我需要使用的选项)

我想做什么:用户输入一个年级级别并为一个类别打分。根据这些分数和年级水平的总和,我需要比较它们以获得另外两个分数示例代码:

if ($grade == 1  && $sumScore <= 5)
 {
   $textscore = 'Beginning';
 }
 if ($grade ==1 && ($sumScore>5 && $sumScore <=8)) 
  {
   $textScore = 'Intermediate';
  }

等。。。。

有 13 个年级 (K-12) 和 4 个类别,我需要用他们自己的"原始分数"来考虑获得这些其他分数。如何避免使用大量的 If/Else if 语句?

谢谢!!

您可以使用 13x4 的二维数组。然后,您可以使用嵌套的 for 循环来遍历每种可能性,并且只有一个语句由于 for 循环而运行了很多次。

例如,数组可能如下所示:

$textscores = array (
  1 => array(5 => 'Beginning', 8 => 'Intermediate', ...),
  ...
  3 => array(5 => 'Intermediate', ...),
  ...
);

嵌套的 for 循环可能如下所示:

foreach($textscores as $grade => $scores) {
  foreach($scores as $sumScore => $textScore) {
    if($userGrade == $grade &&  $userSumScore <= $sumScore) {
      $userTextScore = $textScore;
      break 2;
    }
  }
}

我还没有测试过这个(对不起),但我认为像这样的东西

function getTextScore($grade, $sum) {
    $rules = array( array("grade" => 1, "minSum" => null, "maxSum" => 5, "textScore" => "Beginning"),
                    array("grade" => 1, "minSum" => 6, "maxSum" => 8, "textScore" => "Intermediate" ),
                /* ... */
                );

    for ($ruleIdx=0; $ruleIdx<count($rules); $ruleIdx++) {
        $currentRule = $rules[$ruleIdx];
        if (($currentRule['grade'] == $grade) &&
            ((is_null($currentRule['minSum'])) || ($currentRule['minSum'] <= $sum)) &&
            ((is_null($currentRule['maxSum'])) || ($currentRule['maxSum'] >= $sum))) {
            return $currentRule['textScore'];
        }
    }
    // got to the end without finding a match - need to decide what to do
}

规则具有可选的最小值和最大值。 一旦找到匹配项,它就会停止,因此顺序很重要。 您需要确定是否没有匹配的规则。 您应该能够在不更改逻辑的情况下删除额外的规则或更改现有规则。

从您的示例中,我会建议以下内容

多维数组,但与构造数组的方式略有不同

// Grade => [Text => [Min,Max]]
$textScores = [
    1 => [
        'Beginning'    => [0, 5],
        'Intermediate' => [5, 8],
        'Master'       => [8, 10]
    ],
    2 => [
        'Beginning'    => [0, 7],
        'Intermediate' => [7, 8],
        'Master'       => [8, 10]
    ],
    3 => [
        'Beginning'    => [0, 3],
        'Intermediate' => [3, 6],
        'Master'       => [6, 10]
    ]
];
// Random input to test
$grade    = rand(1, 3);
$sumScore = rand(0, 10);
foreach ($textScores[$grade] as $Text => $MinMax) {
    if ($MinMax[0] <= $sumScore && $MinMax[1] >= $sumScore) {
        $textScore = $Grade;
        break;
    }
}