我正在用PHP生成某些项目。长话短说-我将带有漂亮工具提示的对象保存到一个变量中。我已经生成了100多个项目。所以我有一个巨大的下拉式html选择所有的项目。当用户选择所需的项目时,他转到Generate按钮。在后端,我拿起响应,我想返回客户选择的商品。我正在考虑一个switch语句,它对应于html select的name值,并且我将它与我的变量中的适当项进行匹配。经过测试,它工作得很好。然而,如果我想包括我的所有物品,这将意味着数百个开关案例。如果Switch是我唯一可行的选择,我可以接受,但有没有什么方法可以自动创建switch案例?否则,我将需要手动记录所有的开关情况
switch ($helm){
case "harle":
$helm = $random_harle;
break;
case "eth_harle":
$helm = $random_harle_eth;
break;
case "perfect_harle":
$helm = $perfect_harle;
break;
case "perfect_harle_eth":
$helm = $perfect_harle_eth;
break;
// and a 100+ more of these
default:
$helm = "None";
}发布于 2020-05-26 18:35:14
您可以将所有项映射到一个数组中
$myitems = ["harle" => $random_harle,
.....
];然后使用
foreach ($myitems as $key => $value)
{
if ($key == $helm)
return $value;
}
return "None";这将使用$key测试给定的$helm。如果存在匹配,则返回$value。
在循环(不匹配)之后,您可以返回默认值。
此外,正如CBroe建议的那样,更短的版本将是
if (array_key_exists($helm, $myitems))
return $myitems[$helm];
return "None";https://stackoverflow.com/questions/62020021
复制相似问题