【问题标题】:Getting the latest 6 months in ascending order按升序获取最近 6 个月
【发布时间】:2019-05-14 04:39:09
【问题描述】:

目标:让月份按升序显示在图表中 [例如; 2018 年 12 月、2019 年 1 月、2019 年 2 月]

我在这里尝试了解决方案:

PHP: get last 6 months in format month year

这很好用,只是它按降序显示月份。

所以我尝试重写该代码以按升序显示。

原代码:

<?php
echo date('F, Y');
for ($i = 1; $i < 6; $i++) {
  echo date(', F Y', strtotime("-$i month"));
}
?>

这是我尝试过的:

<?php

$sixMonthAgo = date("F Y",strtotime("-5 month")); // To get the month 6 month ago

echo $sixMonthAgo;
for ($i = 1; $i < 6; $i++) {
  echo date(', F Y', strtotime("-$i month"));
}

?>

但我意识到我的逻辑在这里完全错误。确实,我在$sixMonthAgo 中得到了 6 个月前的月份,但我的循环逻辑是错误的。

我的循环是获取当前日期,然后将月份相应地减去 i 值。如何将该日期替换为 $sixMonthAgo 的值。

类似这样的:echo test(', F Y', strtotime("+$i month"));

【问题讨论】:

    标签: php


    【解决方案1】:

    从高到低迭代。我认为这会奏效。

    <?php
    echo date('F, Y');
    for ($i = 5; $i >= 0; $i--) {
      echo date(', F Y', strtotime("-$i month"));
    }
    ?>
    

    【讨论】:

    • 太棒了!谢谢。
    猜你喜欢
    • 2016-03-28
    • 2021-12-01
    • 1970-01-01
    • 2019-12-02
    • 2022-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2017-08-06
    相关资源
    最近更新 更多