条件三元运算符故障 (PHP)

Conditional ternary operator malfunctions (PHP)

我已经构建了一个函数来将给定的 Y-m-d 日期更改为这样的格式:2016-07-02 到这种格式:July 2nd.

代码:

// Format the given Y-M-D date
function format_date($date) {
    // Parse the date
    list($year, $month, $day) = array_values(date_parse($date));

    // Give the appropriate subscript to the day number
    $last_char = substr($day, -1);
    $pre_last_char = (strlen($day) > 1) ? substr($day, -2, -1) : null;
    $subscript = ($last_char === "1") ? "st" :
                 ($last_char === "2") ? "nd" :
                 ($last_char === "3") ? "rd" : "th";
    $subscript = ($pre_last_char === "1") ? "th" : $subscript;
    $day .= $subscript;

    // Get the month's name based on its number
    $months = [
        "1" => "January",
        "2" => "February",
        "3" => "March",
        "4" => "April",
        "5" => "May",
        "6" => "June",
        "7" => "July",
        "8" => "August",
        "9" => "September",
        "10" => "October",
        "11" => "November",
        "12" => "December"
    ];
    $month = $months[$month];

    // Omit the year if it's this year and assemble the date
    return $date = ($year === date("Y")) ? "$month $day $year" : "$month $day";
}

函数按预期运行,但有一个问题。 $subscript returns "rd" 的第一个条件三元运算符,用于每个以 12.

结尾的数字

示例:

echo format_date("2016-01-01"); // It will output January 1rd

我该如何解决?

不是您问题的直接答案,但如果您只需要像示例中那样的英语,则可以使用 php 的标准 date 函数:

echo date('F jS', strtotime('2016-01-01'));

输出:

January 1st

看到一个working example here

Documentation 读作:

Note: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

这是因为 PHP 弄错了三元运算符 - 它是 left-associative instead of the right-associative of C, Java and so forth。因此,当将 C 代码转换为 PHP 时,您必须将 "true" 和 "false" 表达式括起来。