du958642589 2018-10-05 15:00
浏览 530

PHP - 计算一个数组中的值出现在另一个数组中的次数,然后创建一个包含这些数字的数组

I have two arrays, both in Y-m-d format. One array is the amount of days that has passed in the current month, and one array is a list of when every user on my app has been created in Y-m-d format. I want to create a third array which counts the amount of times a user was created on a certain day in my days-of-month array, then puts that count into the third array.

My code so far is this:

$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));

The $dates array has:

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)

The $dateTimes array has:

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)

I want the third array to loop through all the days in $dates and for every date there is no tally put a 0, so given the above data my array would look like this:

$matches = [0, 1, 0, 2, 0]

I've tried a bunch of PHP array functions but I was wondering if someone could quickly help me out.

  • 写回答

2条回答 默认 最新

  • duanbi8529 2018-10-05 15:12
    关注

    Try something like this:

    // 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;
    }
    

    If you're using PHP 7.x you can use $matches[$key] = $registrations[$date] ?? 0; to shorten it a bit.

    评论

报告相同问题?

悬赏问题

  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)