【问题标题】:PHP - Count the amount of times the value in one array appears in another array, then create an array containing the numbersPHP - 计算一个数组中的值出现在另一个数组中的次数,然后创建一个包含数字的数组
【发布时间】:2019-03-11 03:03:36
【问题描述】:

我有两个数组,都是 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 中的所有日期,并且对于每个日期都没有计数放置一个 0,因此鉴于上述数据,我的数组将如下所示:

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

我尝试了一堆 PHP 数组函数,但我想知道是否有人可以快速帮助我。

【问题讨论】:

    标签: php arrays laravel laravel-5 php-7


    【解决方案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; 将其缩短一点。

    【讨论】:

    • 谢谢,效果很好,你能给我一个链接,让我可以像你一样研究缩短代码吗?我看到这一切,但我不完全理解它
    【解决方案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);
    }
    

    【讨论】:

    • 这个问题被标记为 Laravel!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多