php - 将索引转换为指定字符串的更简洁方法?

标签 php switch-statement

我能否以更简洁的方式实现这一目标?真的会很受欢迎。

    switch($vocation) {

        case 1: $vocation = "Sorcerer";        break;
        case 2: $vocation = "Druid";           break;       
        case 3: $vocation = "Paladin";         break;           
        case 4: $vocation = "Knight";          break;           
        case 5: $vocation = "Master Sorcerer"; break;           
        case 6: $vocation = "Elder Druid";     break;           
        case 7: $vocation = "Royal Paladin";   break;           
        case 8: $vocation = "Elite Knight";    break;

    }

谢谢!

很抱歉找不到更好的标题

最佳答案

您可以使用数组代替 switch 语句。

$vocations = array("Sorcerer", "Druid" ...);
$vocationStr = $vocations[$vocation - 1];

或者

$vocations = array(1 => "Sorcerer", 2 => "Druid" ...);
$vocationStr = $vocations[$vocation];

就我个人而言,我反对重用 $vocation 来引用两种类型(整数和字符串),因为它们很可能是您程序中的两个不同概念。

我还建议改为为这些值创建枚举类型,但这取决于上下文。

关于php - 将索引转换为指定字符串的更简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1757665/

相关文章:

php - AJAX load more posts script out put nothing, no warnings, no notices, 没有数据

php - 我有 2 个输入时间字段,我希望输入 01 :00 AM in 1st input field time then in 2nd input field time it should be only 02:00AM

ios - Swift:UIButton textLabel.text 值在 switch 语句中不可用

linux - 开关连接不工作

java - 带有 "and"/"or"JAVA 的多变量 Switch 语句

php - 此集合实例上不存在属性 [title]

php - 使用 Ruby、PHP 或 Python 的音频水印

php - 登录 PHP webapp

Java switch 语句 - 行为困惑

java - 应用程序崩溃: Attempt to invoke virtual method on a null object reference