php - 我有 100 多个 if 语句。我可以/应该使用 foreach 还是其他东西?
问题描述
我有一个向用户提问的表格,每个问题都有一个可以选择的复选框。
例如
- 你想知道苹果吗?
- 复选框:“是”
- 你想了解紫色吗?
- 复选框:“是”
- 你想知道乔治华盛顿吗?
- 复选框:“是”
提交表单后,每个复选框都会有一段文本输出。
例如,如果用户检查关于“apples”的问题和关于“George Washington”的问题,那么在他们提交表单后,他们将看到:
- 这是一段关于苹果的文字。
- 这是一段关于乔治华盛顿的文字。
如果有代码可以得到我想要的输出,但它涉及到每个问题都有一个 if 语句——大约有 100 个问题——所以我想知道是否有更有效/更复杂的方法。
问题字段元名称和值如下所示:
- my_prefix_apples(值:苹果)
- my_prefix_purple(值:紫色)
- my_prefix_george_washington(值:乔治华盛顿)
这是我的代码,仅以上述三个问题为例:
// 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 语句,但我找不到正确的方法。它要么中断,要么不输出任何东西。
解决方案
使用关联数组会更好,所以关键是问题,值是文本。
$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>";
推荐阅读
- google-apps-script - 我的 Google App Script 下面是否有与 Google Slides 相关联的修复程序
- c# - UWP Directory.CreateDirectory 中的 UnauthorizedAccessException
- docker - 在 Docker 和 Nginx 中使用反向代理时出现 502 Bad Gateway
- django - 在 Django-Filter/DRF 中获取“今天”数据
- html - 具有全宽项目的水平滚动弹性列表
- c# - 区分进入我的服务总线队列的数据
- linux - 如何知道 EINTR 的来源?
- python - 输入此帖子的 URL 时显示 Instagram 帖子 (Python | Tkinter)
- r - r bookdown favicon 离线工作但不能在线
- android - android:buttonStyle 停止使用材料设计 1.2.0