drtj40036 2017-02-17 04:04
浏览 71
已采纳

laravel carbon从集合的日期列中获取日期名称

I have this collection from a database where I have a column called "event_date".

What I want is just to get only the day names from that column that comes in a collection.

I know you can use Carbon to get the name days through, for example, a method called ->format(), however I get an error saying that this method does not exist.

My code so far is as follows:

$collection = MyModel::all();

Inside there is the "event_date" property or column. From that, I want to get the names of the days to put them into an array or collection and finally count those days frequencies.

In order to achieve this I have tried the following:

I tried the ->pluck() method as follows:

$filtered = collect([
            'myDates'=>$collection->pluck('event_date'),
        ]);

And the dd($filtered) looks like as follows:

Collection {#209 ▼
  #items: array:1 [▼
    "myDates" => Collection {#243 ▼
      #items: array:30 [▼
        0 => Carbon {#244 ▼
          +"date": "2017-02-05 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        1 => Carbon {#218 ▼
          +"date": "2017-01-15 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        2 => Carbon {#250 ▼
          +"date": "2016-09-25 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        3 => Carbon {#249 ▼
          +"date": "2016-05-22 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
...

I tried to get the day names as follows:

$Daynames = $filtered->each(function($item,$key){
            return $item->myDates->format('l');
        });

But I got the following error:

Undefined property: Illuminate\Support\Collection::$myDates

Any ideas to get only the daynames into an array or collection? Is there another way to do this?

  • 写回答

3条回答 默认 最新

  • dps69208 2017-02-17 04:22
    关注

    You're calling format() on the collection of dates, while you should call it on the Carbon objects. You need another loop that would go through all dates in myDates collection and format them, e.g.:

    $Daynames = [];
    $filtered->each(function($item,$key) use (&$Daynames) {
      $item->each(function($date) use (&$Daynames) {
        $Daynames[] = $date->format('l');
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果