如何创建翻译函数作为可用于数组中元素的方法

how to create translate function as a method usable for an element in array

我有一个包含考试数据的数组,每次考试只有 4 种类型中的 1 种类型 [iq,math,geo,gen] 我是这样得到的 {{ $exam->type }} 我只想添加翻译方法到类型,所以当我写 $exam->type->translate() 时,我得到翻译的词,函数结构将如何以及我应该在哪里写它,在 Exam 模型或页面控制器中...

翻译功能:

function translate($word){
  return $word == "math" 
             ? "ماث" 
             : $word == "iq" 
             ? "آيكيو" 
             : $word == "geo"
             ? "هندسة"
             : $word == "gen"
             ? "شامل"
             : "غير معرّف"
}

不要那样嵌套三元组。阅读和解决都是一团糟,因为您很容易将优先级弄错(另外,自 PHP 7.4 以来,您需要将嵌套的三元组与括号分组,否则您将收到弃用警告或致命错误PHP8)

如果您更愿意手动操作(而不是使用 Laravel 的翻译功能,这可能会被推荐),您可以使用数组使其更容易:

function translate($word)
{
    $words = [
        "math" => "ماث",
        "iq"   => "آيكيو", 
        "geo"  => "هندسة",
        "gen"  => "شامل",
    ];

    // Check if the word exists in the array and return it 
    // if it doesn't exist, return the default
    return $words[$word] ?? "غير معرّف";
}