Search code examples
phparrayslaravelcountgrouping

Group same date and count together


I have done a code to call an array of a value based on each date. My code is below:

$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
$array[] = [];
foreach ($matchs as $key => $match) {
    $array[$match->date_access] = $match->status;
}

dd($array);

Using this I try and dd(); I get output like this: enter image description here

What I'm trying to do now is to first group the same dates together and also I want to then count the total for that dates. how can I do this?


Solution

  • Not sure what you mean with "date". But if you mean the same day it would be this:

    $matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
    $array[] = [];
    foreach ($matchs as $key => $match) {
     $day = substr($match->date_access, 0, 10);
     if(isset($array[$day])){
      $array[$day]++;
     }else{
      $array[$day] = 1;
     }
    }
    
    dd($array);