在我的Laravel 5.1应用程序中,我有一个Subscription功能。它在某种程度上起作用,但不是我想要的......
场景:用户在2016年10月订阅了6个月。所以,数组看起来像这样:
[
"subscription_months" => 6
"subscription_start_month" => "01-10-2016" // <-- will be carbon instance
"subscription_end_month => "31-03-2017" // <-- will be carbon instance
"monthName" => "October"
]
我展示的上述数组只有1个月..数组中还有5个元素..
我想要的是,我想在Year
monthName
所以,它看起来像这样。
[
[
"monthName" => "October, 2016" // <-- for 1st month
]
[
"monthName" => "November, 2016" // <-- for 2nd month
]
[
"monthName" => "December, 2016" // <-- for 3rd month
]
[
"monthName" => "January, 2017" // <-- for 4th month
]
[
"monthName" => "February, 2017" // <-- for 5th month
]
[
"monthName" => "March, 2017" // <-- for 6th month
]
]
到目前为止,我尝试过的代码是:
$startMonthForMixed = $invoice->subscription_start_date->month;
for($i = 0; $i < $invoice->subscription_months; $i++) {
$convertedInvoices[] = [
'id' => $invoice->id,
'order_code' => $invoice->order_code,
'order_type' => 'Mixed - Subscription',
'subscription_months' => $invoice->subscription_months,
'subscription_start_month' => $invoice->subscription_start_date,
'subscription_end_month' => $invoice->subscription_end_date,
'monthName' => date("F", mktime(0, 0, 0, $startMonthForMixed, 01)) . ", " . Carbon::now()->addYear()
];
$startMonthForMixed++;
}
有人可以帮帮忙吗?提前谢谢。
答案 0 :(得分:0)
您尝试过的代码将始终使用当前年份,因此如果订阅期限为另一年,则无法使用。
您可以在代码中使用此变体,这会使用一些Carbon和DateTime方法:
// take copy of start date
$subscription_month = $invoice->subscription_start_date->copy();
for($i = 0; $i < $invoice->subscription_months; $i++) {
$convertedInvoices[] = [
'id' => $invoice->id,
'order_code' => $invoice->order_code,
'order_type' => 'Mixed - Subscription',
'subscription_months' => $invoice->subscription_months,
'subscription_start_month' => $invoice->subscription_start_date,
'subscription_end_month' => $invoice->subscription_end_date,
'monthName' => $subscription_month->format("F, Y")
];
// move to first date of following month
$subscription_month->modify('first day of next month');
}
答案 1 :(得分:0)
您可以使用Carbon对象的add
方法添加1个月来循环显示月数。然后,格式化只是调用format
方法的问题,正如trincot已经提出的那样