我有两个数组,均为Y-m-d格式。一个数组是当月过去的天数,一个数组是我的应用程序上的每个用户以Y-m-d格式创建的时间的列表。我想创建第三个数组,该数组计算我的月份数组中某天在某天创建用户的次数,然后将其放入第三个数组。
到目前为止,我的代码是:
$daysInCurrentMonth = date('t');
$daysPast = date('j');
$month = date('m');
$year = date('y');
$participants = DB::table('participants')->get();
$createdAt = $participants->pluck('created_at');
foreach($createdAt as $created)
{
$dateTimes[] = Carbon::createFromFormat('Y-m-d H:i:s', $created)->format('Y-m-d');
}
$dates = $this->generateDateRange(Carbon::parse($year.'-'.$month.'-01'), Carbon::parse($year.'-'.$month.'-'.$daysPast));
$ dates数组具有:
array (size=5)
0 => string '2018-10-01' (length=10)
1 => string '2018-10-02' (length=10)
2 => string '2018-10-03' (length=10)
3 => string '2018-10-04' (length=10)
4 => string '2018-10-05' (length=10)
$ dateTimes数组具有:
array (size=6)
0 => string '2018-09-21' (length=10)
1 => string '2018-09-24' (length=10)
2 => string '2018-09-24' (length=10)
3 => string '2018-10-02' (length=10)
4 => string '2018-10-04' (length=10)
5 => string '2018-10-04' (length=10)
我希望第三个数组在$ dates的所有日期中循环播放,并且对于每个日期都没有记号,因此给定上述数据,我的数组将如下所示:
$matches = [0, 1, 0, 2, 0]
我已经尝试了很多PHP数组函数,但是我想知道是否有人可以快速地帮助我。
答案 0 :(得分:2)
// the final array that holds umber of times user was created.
// as a key value pair ( 2018-01-01 => 5 )
$counts = [];
foreach ($dates as $date) {
$count = 0;
foreach ($dateTimes as $dateTime) {
if ($date == $dateTime) $count++;
}
array_set($counts, $date, $count);
}
答案 1 :(得分:1)
尝试这样的事情:
// Groups $dateTimes by number of occurrences
$registrations = array_count_values($dateTimes);
$matches = [];
foreach ($dates as $key => $date) {
$matches[$key] = isset($registrations[$date]) ? $registrations[$date] : 0;
}
如果您使用的是PHP 7.x,则可以使用$matches[$key] = $registrations[$date] ?? 0;
来将其缩短一点。