[英]PHP array containing 12 months and start with current month and decrement
我正在嘗試獲取從當前月份開始的 12 個月的數組,遞減並類似於“2022 年 3 月”。
這是我的代碼:
$months = array();
$count = 0;
while ($count <= 11) {
$months[] = date('M Y', strtotime("-".$count." month"));
$count++;
}
但是對於天數較少的月份有一些問題。 例如: dd($months[0]) => "Mar 2022"
和dd($months[1]) => "Mar 2022"
必須是 "Feb 2022"。
使用碳。
use Carbon\Carbon;
for ($i = 0; $i < 12; $i++) {
array_push($months, Carbon::now()->subMonth($i)->format('M Y'));
};
一種快速解決方案如下:
<?php
$months = array();
$count = 0;
while ($count <= 11) {
$prevMonth = ($count == 1) ? "first day of previous month" : "-$count month";
$months[] = date('M Y', strtotime($prevMonth));
$count++;
}
參考: 在 php 中獲取上個月的日期
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.