我試圖從當前月份開始獲得 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"必須是“2022 年 2 月”。
uj5u.com熱心網友回復:
一種快速的解決方案如下:
<?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中獲取上個月的日期
uj5u.com熱心網友回復:
使用碳。
use Carbon\Carbon;
for ($i = 0; $i < 12; $i ) {
array_push($months, Carbon::now()->subMonth($i)->format('M Y'));
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452472.html
下一篇:Laravel9-[Route:trial.show][URI:evaluation/{evaluation}/trial/{trial}][缺少引數:trial]缺少必需引數
