Search code examples
phplaravelgrouping

Get values from multiple database tables and group by day of the week using Laravel


I want to insert data in array in this format.

day1[
  screen1 [  ]
  screen2 [  ]
]
day1[
   screen1 [  ]
   screen2 [  ]
]

So far I have tried:

for ($i = 0; $i < 7; $i++) {
    $date = Carbon::now()->addDays($i)->format('Y-m-d');
    $a = strtotime($date);
    $days[] = date('l', $a);
    $screen = screen::pluck('id')->toArray();
    for ($j = 0; $j < count($screen); $j++) {
         $showTime[] = ScheduledMovie::Where('movie_id', $id)
             ->Where('show_date', $date)
             ->Where('show_day', $days[$i])
             ->where('screen_id', $screen[$j])
             ->pluck('show_time_start')
             ->toArray();
    }
}

The table used are schedule_table, Movie_table, and screen_table. The Movie table and schedule table have a one-to-many relation. My target is to extract the showtime of a particular day for a particular screen from the schedule table. So far I am able to extract the showtime of particular day.


Solution

  • $dayScreenArr = [];
    for($i=0;$i<7;$i++){
        $date = Carbon::now()->addDays($i)->format('Y-m-d');
        $a = strtotime($date);
        $days[]=date('l',$a);
        $dayScreenArr[$i]['day'.$i][] = $days;
        $screen = screen::pluck('id')->toArray();
        for($j=0;$j<count($screen);$j++){
             $showTime[] =ScheduledMovie::Where('movie_id',$id)->Where('show_date',$date)->Where('show_day',$days[$i])->where('screen_id',$screen[$j])->pluck('show_time_start')->toArray();
             $dayScreenArr[$i]['day'.$i]['screen'.$i][] = $showTime;
        }
    }
    /* check this */
    echo "<pre>";
    print_r($dayScreenArr);