Search code examples
phparraysfilteringgroupinghierarchical-data

Group and filter multidimensional array by date


I have a movies array that I'm trying to use to display a calendar page based on dates. Here's the array:

$movies = [
    'MOVIE TITLE #1' => [
        'id' => 11990,
        'times' => [
            '2023-06-03' => [
                '11:00am',
                '2:30pm',
                '6:00pm',
                '9:30pm',
            ],
            '2023-06-04' => [
                '12:30pm',
                '4:00pm',
                '7:30pm',
            ],
            '2023-06-06' => [
                '12:30pm',
                '4:00pm',
                '7:30pm',
            ],
        ],
    ],
    'MOVIE TITLE #2' => [
        'id' => 11892,
        'times' => [
            '2023-06-03' => [
                '12:00pm',
                '3:30pm',
                '7:00pm',
            ],
        ],
    ],
];

I have another array that generates the list of dates that have movies playing on them. This is used to populate a form dropdown to show/hide DIVS for each date with movies showing.

I need help with taking the date from that other array to search this array for any movies playing on that date -- so that I can generate a DIV for each date with a list of the movies and times in this format:

2023-06-03 (DIV)

  • MOVIE TITLE #1
    • 11:00am
    • 2:30pm
    • 6:00pm
    • 9:30pm
  • MOVIE TITLE #2
    • 12:00pm
    • 3:30pm
    • 7:00pm

2023-06-04 (DIV)

  • MOVIE TITLE #1
    • 12:30pm
    • 4:00pm
    • 7:30pm ...

Can someone provide a basic coding example?


Solution

  • Iterate over your movies array to access the titles and their respective dates and times.

    For each encountered title, filter the dates by your other array of dates. There are many ways to do this filtration.

    Finally, push the time elements into the hierarchical result array.

    I'll leave the HTML markup generation to you.

    Code: (Demo)

    $dates = array_flip(['2023-06-03', '2023-06-04']);
    
    $result = [];
    foreach ($movies as $title => ['times' => $times]) {
        foreach (array_intersect_key($times, $dates) as $date => $times) {
            $result[$date][$title] = $times;
        }
    }
    var_export($result);
    

    Output:

    array (
      '2023-06-03' => 
      array (
        'MOVIE TITLE #1' => 
        array (
          0 => '11:00am',
          1 => '2:30pm',
          2 => '6:00pm',
          3 => '9:30pm',
        ),
        'MOVIE TITLE #2' => 
        array (
          0 => '12:00pm',
          1 => '3:30pm',
          2 => '7:00pm',
        ),
      ),
      '2023-06-04' => 
      array (
        'MOVIE TITLE #1' => 
        array (
          0 => '12:30pm',
          1 => '4:00pm',
          2 => '7:30pm',
        ),
      ),
    )