如何重构以下代码以使其更简洁且更易于维护?
if ($row['vocation'] == 1) $vocation = "sorcerer";
if ($row['vocation'] == 2) $vocation = "druid";
if ($row['vocation'] == 3) $vocation = "paladin";
if ($row['vocation'] == 4) $vocation = "knight";
if ($row['vocation'] == 5) $vocation = "master sorcerer";
if ($row['vocation'] == 6) $vocation = "elder druid";
if ($row['vocation'] == 7) $vocation = "royal paladin";
if ($row['vocation'] == 8) $vocation = "elite knight";
else $vocation = "none";
最佳答案
我建议使用数组,如下所示:
static $vocations = array(
1 => 'sorceror',
2 => 'druid',
3 => 'paladin',
4 => 'knight',
5 => 'master sorceror',
6 => 'elder druid',
7 => 'royal paladin',
8 => 'elite knight',
);
$vocation =
isset($vocations[$row['vocation']]) ? $vocations[$row['vocation']] : 'none';
关于php - 如何在 PHP 中更轻松地将整数值映射到字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/800518/