首页 > 解决方案 > 我有 100 多个 if 语句。我可以/应该使用 foreach 还是其他东西?

问题描述

我有一个向用户提问的表格,每个问题都有一个可以选择的复选框。

例如

  1. 你想知道苹果吗?
    • 复选框:“是”
  2. 你想了解紫色吗?
    • 复选框:“是”
  3. 你想知道乔​​治华盛顿吗?
    • 复选框:“是”

提交表单后,每个复选框都会有一段文本输出。

例如,如果用户检查关于“apples”的问题和关于“George Washington”的问题,那么在他们提交表单后,他们将看到:

如果有代码可以得到我想要的输出,但它涉及到每个问题都有一个 if 语句——大约有 100 个问题——所以我想知道是否有更有效/更复杂的方法。

问题字段元名称和值如下所示:

这是我的代码,仅以上述三个问题为例:

// Declare the question metas
$questionMetas = [
    'apples',
    'purple',
    'george_washington',
];

// Save the paragraphs of text that will be output
$applesText = "Here is a paragraph of text about apples.";
$purpleText = "Here is a paragraph of text about purple.";
$georgeText = "Here is a paragraph of text about George Washington.";

// Use table tag to open the table before looping
echo "<table>";

// Loop over all question metas
foreach ($questionMetas as $questionMeta){
    // Save the question values
    $questions = $fields['my_prefix_' . $questionMeta]['value'];

    // If the current field is empty skip to the next field
    if (empty($questions)){
        continue;
    }

    // For the questions that the user selected,
    // output the paragraphs in a table
    if ($questions === Apples){
        echo "<tr>";
            echo "<td>-</td>";
            echo "<td>$applesText</td>";
        echo "</tr>";
    }
    if ($questions === Purple){
        echo "<tr>";
            echo "<td>-</td>";
            echo "<td>$purpleText</td>";
        echo "</tr>";
    }
    if ($questions === 'George Washington'){
        echo "<tr>";
            echo "<td>-</td>";
            echo "<td>$georgeText</td>";
        echo "</tr>";
    }
}

// Close table
echo "</table>";

我一直在尝试用另一个 foreach($questions 作为 $question)和一个 switch 替换 100+ if 语句,但我找不到正确的方法。它要么中断,要么不输出任何东西。

标签: php

解决方案


使用关联数组会更好,所以关键是问题,值是文本。

$questionMetas = [
    'apples' => "Here is a paragraph of text about apples.",
    'purple' => "Here is a paragraph of text about purple.",
    'george_washington' => "Here is a paragraph of text about George Washington."
];

然后输出只是意味着将相关文本$questions用作键...

    echo "<tr>";
        echo "<td>-</td>";
        echo "<td>{$questionMetas[$questions]}</td>";
    echo "</tr>";

推荐阅读