我正在从API中提取变量字符串Rarity
。
然后,我需要根据收到的内容缩短此字符串。所以我使用了一个很大的if / else块:
if($rarity == "Common"){
$rarestring = "(C)";
}else if($rarity == "Rare"){
$rarestring = "(R)";
}else if($rarity == "Super Rare"){
$rarestring = "(SR)";
}else if($rarity == "Holofoil Rare"){
$rarestring = "(HFR)";
}else if($rarity == "Ultra Rare"){
$rarestring = "(UR)";
}else if($rarity == "Ultimate Rare"){
$rarestring = "(UtR)";
}else if($rarity == "Secret Rare"){
$rarestring = "(ScR)";
}else if($rarity == "Ultra Secret Rare"){
$rarestring = "(UScR)";
}else if($rarity == "Secret Ultra Rare"){
$rarestring = "(SCuR)";
}else if($rarity == "Prismatic Secret Rare"){
$rarestring = "(PScR)";
}else if($rarity == "Ghost Rare"){
$rarestring = "(GR)";
}else if($rarity == "Parallel Rare"){
$rarestring = "(PR)";
}else if($rarity == "Parallel Common"){
$rarestring = "(PC)";
}else if($rarity == "Super Parallel Rare"){
$rarestring = "(SPR)";
}else if($rarity == "Ultra Parallel Rare "){
$rarestring = "(UPR)";
}else if($rarity == "Duel Terminal Parallel Common"){
$rarestring = "(DPC)";
}else if($rarity == "Duel Terminal Rare Parallel Rare"){
$rarestring = "(DRPR)";
}else if($rarity == "Duel Terminal Super Parallel Rare"){
$rarestring = "(DSPR)";
}else if($rarity == "Duel Terminal Ultra Parallel Rare"){
$rarestring = "(DUPR)";
}else if($rarity == "Duel Terminal Secret Parallel Rare"){
$rarestring = "(DScPR)";
}else if($rarity == "Gold Rare"){
$rarestring = "(GUR)";
}
我不禁觉得这不是最佳选择。我知道,通常情况下,性能提升不是很重要,但我觉得这可能是学习并可能做得更好的好机会。
我认为我可以将所有稀有物放入一个数组中,但是我仍然遇到相同的问题,需要比较然后缩短。
答案 0 :(得分:2)
是的,使用数组映射:
$options = [
'Common' => '(C)',
'Rare' => '(R)',
];
//...
if (!isset($options[$rarity])) {
throw new Exception('Unknown rarity ' . $rarity);
}
$rarestring = $options[$rarity];
或者您可以使用switch构造:
switch($rarity) {
case 'Common': $rarestring = '(C)'; break;
case 'Rare': $rarestring = '(R)'; break;
default: throw new Exception('Unknown rarity ' . $rarity);
}
编辑:
对于那些可能会读到这的人来说,这是未来。 与许多人所说的相反,该数组总是更好,这两种方法(数组与切换)之间存在真正的区别,不同之处在于它是用代码编写的。
Switch的行为非常类似于elseif序列-它允许每种情况执行一个代码块,而最后一种情况花费的时间最多,因为以前的所有情况都必须与针进行比较($ rarity in上面的情况)。时间复杂度O(n)。内存复杂度O(1)。
另一方面,当每种情况都应返回预定义的值时,数组仅允许用例。并且在PHP数组中实现为哈希表,其中密钥查找t的时间复杂度为O(1)
答案 1 :(得分:1)
您可以这样做,
$arr = [
"Common" => "(C)",
"Rare" => "(R)",
"Super Rare" => "(SR)",
"Holofoil Rare" => "(HFR)",
"Ultra Rare" => "(UR)",
"Ultimate Rare" => "(UtR)",
"Secret Rare" => "(ScR)",
"Ultra Secret Rare" => "(UScR)",
"Secret Ultra Rare" => "(SCuR)",
"Prismatic Secret Rare" => "(PScR)",
"Ghost Rare" => "(GR)",
"Parallel Rare" => "(PR)",
"Parallel Common" => "(PC)",
"Super Parallel Rare" => "(SPR)",
"Ultra Parallel Rare " => "(UPR)",
"Duel Terminal Parallel Common" => "(DPC)",
"Duel Terminal Rare Parallel Rare" => "(DRPR)",
"Duel Terminal Super Parallel Rare" => "(DSPR)",
"Duel Terminal Ultra Parallel Rare" => "(DUPR)",
"Duel Terminal Secret Parallel Rare" => "(DScPR)",
"Gold Rare" => "(GUR)",
];
echo ($arr[$rarity] ?? 'nothing');
您无需为此编写任何开关或if-else块。