【问题标题】:Conditional ternary operator malfunctions (PHP)条件三元运算符故障 (PHP)
【发布时间】:2016-11-04 19:48:45
【问题描述】:

我已经构建了一个函数来将给定的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 的第一个条件三元运算符为每个以 12 结尾的数字返回 "rd"

例子:

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

我该如何解决这个问题?

【问题讨论】:

  • 使用daysuf
  • 如果您只想修复您的代码,take a look。检查单行版本以获得更好的视觉效果,了解我打开/关闭的位置(和)。
  • 谢谢@FirstOne。我检查了你的修复。我将编辑这个问题以帮助将来可能偶然发现它的任何人。

标签: php ternary-operator


【解决方案1】:

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

【讨论】:

  • 非常感谢@Antti 的链接。
【解决方案2】:

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

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

输出:

1 月 1 日

查看working example here

【讨论】:

  • 谢谢@jeroen。我不知道这个功能。点赞!
【解决方案3】:

Documentation 读作:

注意:建议您避免“堆叠”三元表达式。 在一个内使用多个三元运算符时 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.
?>

【讨论】:

  • Alex,感谢您在回答中提供的详细信息。由于括号不正确,我似乎又一次落入了同一个陷阱。我试过你的建议,效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
  • 2013-04-26
  • 2013-06-06
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2015-05-20
相关资源
最近更新 更多