使用三元组查找完整月份名称(PHP)

sof*_*kid 0 php if-statement short

我试图通过在PHP中使用此技术来更改值,但它不起作用!不幸的是,我也不知道这种技术的名称.因此限制我在谷歌搜索解决方案.

echo $session_slct->f("theMonth") == '01' ? "January" ||
     $session_slct->f("theMonth") == '02' ?  "February" ||
     $session_slct->f("theMonth") == '03' ?  "March" || 
     $session_slct->f("theMonth") == '04' ?  "April" || 
     $session_slct->f("theMonth") == '05' ?  "May" || 
     $session_slct->f("theMonth") == '06' ?  "June" || 
     $session_slct->f("theMonth") == '07' ?  "July" || 
     $session_slct->f("theMonth") == '08' ?  "August" || 
     $session_slct->f("theMonth") == '09' ?  "September" || 
     $session_slct->f("theMonth") == '10' ?  "October" || 
     $session_slct->f("theMonth") == '11' ?  "November" || 
     $session_slct->f("theMonth") == '12' ?  "December"  : "Invalid Month!";
Run Code Online (Sandbox Code Playgroud)

Xae*_*ess 5

我想你想要:

// $month_num is in separate variable in case $session_slct->f("theMonth") is i.e. slow operation or using external resource
$month_num = $session_slct->f("theMonth");
echo ($month_num == '01') ? "January" :
     ($month_num == '02') ?  "February" :
     ($month_num == '03') ?  "March" :
     ($month_num == '04') ?  "April" :
     ($month_num == '05') ?  "May" :
     ($month_num == '06') ?  "June" :
     ($month_num == '07') ?  "July" :
     ($month_num == '08') ?  "August" :
     ($month_num == '09') ?  "September" :
     ($month_num == '10') ?  "October" :
     ($month_num == '11') ?  "November" :
     ($month_num == '12') ?  "December"  : "Invalid Month!";
Run Code Online (Sandbox Code Playgroud)

甚至:

switch ($session_slct->f("theMonth")) {
    case '01': $month = "January"; break;
    case '02': $month = "February"; break;
    case '03': $month = "March"; break;
    case '04': $month = "April"; break;
    case '05': $month = "May"; break;
    case '06': $month = "June"; break;
    case '07': $month = "July"; break;
    case '08': $month = "August"; break;
    case '09': $month = "September"; break;
    case '10': $month = "October"; break;
    case '11': $month = "November"; break;
    case '12': $month = "December"; break;
    default: $month = "Invalid Month!";
}

echo $month;
Run Code Online (Sandbox Code Playgroud)

但这些并不是真正的DRY选项,您可以使用PhpMyCoder和efritz解决方案;)


Bai*_*ker 5

为什么在有日期时需要三元组或数组映射:

echo date('F', strtotime($month.'/1/2010'));
Run Code Online (Sandbox Code Playgroud)

但如果您坚持使用三元组,请检查PHP.net以获取正确的语法.它应该是:

echo $month == '01' ? 'January' :
     $month == '02' ? 'February' :
     //etc
Run Code Online (Sandbox Code Playgroud)

基本上,||是OR运算符,而不是您需要为三元组指定替代方法的冒号.