はじめに
こんばんは。
Carbonよく使っているのですが、 最近 CarbonPeriodの存在を知りました。
本題
<?php use Carbon\CarbonImmutable; use Carbon\CarbonPeriodImmutable; $period = CarbonPeriodImmutable::create( CarbonImmutable::now()->startOfMonth(), CarbonImmutable::now()->endOfMonth(), ); dd(array_map( static fn(CarbonImmutable $d) => $d->format('Y-m-d H:i:s'), $period->toArray() )); /** array:30 [▼ 0 => "2023-09-01 00:00:00" 1 => "2023-09-02 00:00:00" 2 => "2023-09-03 00:00:00" 3 => "2023-09-04 00:00:00" 4 => "2023-09-05 00:00:00" 5 => "2023-09-06 00:00:00" 6 => "2023-09-07 00:00:00" 7 => "2023-09-08 00:00:00" 8 => "2023-09-09 00:00:00" 9 => "2023-09-10 00:00:00" 10 => "2023-09-11 00:00:00" 11 => "2023-09-12 00:00:00" 12 => "2023-09-13 00:00:00" 13 => "2023-09-14 00:00:00" 14 => "2023-09-15 00:00:00" 15 => "2023-09-16 00:00:00" 16 => "2023-09-17 00:00:00" 17 => "2023-09-18 00:00:00" 18 => "2023-09-19 00:00:00" 19 => "2023-09-20 00:00:00" 20 => "2023-09-21 00:00:00" 21 => "2023-09-22 00:00:00" 22 => "2023-09-23 00:00:00" 23 => "2023-09-24 00:00:00" 24 => "2023-09-25 00:00:00" 25 => "2023-09-26 00:00:00" 26 => "2023-09-27 00:00:00" 27 => "2023-09-28 00:00:00" 28 => "2023-09-29 00:00:00" 29 => "2023-09-30 00:00:00" ] */
めっちゃ楽。
これをもっと早く知りたかった。。。
降順にしたい場合は array_reverse
を使えばできそう
<?php use Carbon\CarbonImmutable; use Carbon\CarbonPeriodImmutable; $period = CarbonPeriodImmutable::create( CarbonImmutable::now()->startOfMonth(), CarbonImmutable::now()->endOfMonth(), ); dd(array_map( static fn(CarbonImmutable $d) => $d->format('Y-m-d H:i:s'), array_reverse($period->toArray()) )); /** array:30 [▼ 0 => "2023-09-30 00:00:00" 1 => "2023-09-29 00:00:00" 2 => "2023-09-28 00:00:00" 3 => "2023-09-27 00:00:00" 4 => "2023-09-26 00:00:00" 5 => "2023-09-25 00:00:00" 6 => "2023-09-24 00:00:00" 7 => "2023-09-23 00:00:00" 8 => "2023-09-22 00:00:00" 9 => "2023-09-21 00:00:00" 10 => "2023-09-20 00:00:00" 11 => "2023-09-19 00:00:00" 12 => "2023-09-18 00:00:00" 13 => "2023-09-17 00:00:00" 14 => "2023-09-16 00:00:00" 15 => "2023-09-15 00:00:00" 16 => "2023-09-14 00:00:00" 17 => "2023-09-13 00:00:00" 18 => "2023-09-12 00:00:00" 19 => "2023-09-11 00:00:00" 20 => "2023-09-10 00:00:00" 21 => "2023-09-09 00:00:00" 22 => "2023-09-08 00:00:00" 23 => "2023-09-07 00:00:00" 24 => "2023-09-06 00:00:00" 25 => "2023-09-05 00:00:00" 26 => "2023-09-04 00:00:00" 27 => "2023-09-03 00:00:00" 28 => "2023-09-02 00:00:00" 29 => "2023-09-01 00:00:00" ] */
終わりに
よく使っているライブラリでも、意外と知らないのがあるんですね〜。
現場からは以上です。