【问题标题】:Laravel collection by monthLaravel 按月收集
【发布时间】:2017-07-17 16:30:45
【问题描述】:

我有一个集合,我需要按月计算的用户总数。

所以我这样做了:

array_replace(array_fill_keys(range(0, 11), 0), $users->groupBy('created_at.month')->toArray())

这有点工作,因为我明白了:

array:12 [▼
  0 => 0
  1 => 0
  2 => 0
  3 => 0
  4 => 0
  5 => 0
  6 => array:1 [▶]
  7 => array:2 [▶]
  8 => 0
  9 => 0
  10 => 0
  11 => 0
]

我现在面临的问题是我不需要67 位置的两个数组,但我需要计数。

所以我在想这样的事情:

$users->groupBy('created_at.month')->count()->toArray();

但是,这显然行不通。有什么想法吗?

【问题讨论】:

  • 试试这个,它可能适用于你的情况count($users->groupBy('created_at.month')->toArray()),不过我不确定
  • @SagarGuatam 不,它会返回一个整数。

标签: php laravel collections


【解决方案1】:

尝试使用map 方法

$collection->map(function ($item, $key) {
    return count($item);
});

【讨论】:

  • 谢谢,最后得到这个:array_replace(array_fill_keys(range(0, 11), 0), $users->groupBy('created_at.month')->map(function($users) { return count($users); })->toArray());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 2017-03-24
相关资源
最近更新 更多