无法实现嵌套三元表达式以将序数后缀添加到格式化日期中的日期[重复]

问题描述 投票:0回答:3

我构建了一个函数来更改给定的

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
的第一个条件三元运算符为每个以
"rd"
1
结尾的数字返回
2

示例:

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

我该如何解决这个问题?

php conditional-statements date-formatting ternary
3个回答
5
投票

文档内容如下:

注意:建议您避免“堆叠”三元表达式。 PHP 在一个表达式中使用多个三元运算符时的行为 单一陈述并不明显:

<?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.
?>

3
投票

这是因为 PHP 的三元运算符错误 - 它是 左关联,而不是 C、Java 等的 右关联。因此,将 C 代码转换为 PHP 时,必须将“true”和“false”表达式放在括号中。


2
投票

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

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

输出:

1月1日

请参阅此处工作示例

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.