Maqk
Maqk

Reputation: 525

Group Days based on matching hours

How might I code a function in PHP to merge days with similar opening hours of a store together. For example, if we have:

Mon  : 9:00AM - 7:00PM
Tue  : 9:00AM - 10:00PM
Wed  : 9:00AM - 7:00PM
Thu  : 9:00AM - 10:00PM
Fri  : 9:00AM - 7:00PM
Sat  : 9:00AM - 10:00PM
Sun  : 9:00AM - 7:00PM

I want the code output as:

Mon,Wed,Fri,Sun - 9:00AM - 7:00PM
Tue,Thu,Sat - 9:00AM - 10:00PM

Below is the code which I'm trying to work out.

$openHours = array(
    'Mon' => '9am-7pm',
    'Tue' => '9am-10pm',
    'Wed' => '9am-7pm',
    'Thu' => '9am-10pm',
    'Fri' => '9am-7pm',
    'Sat' => '9am-10pm',
    'Sun' => '9am-7pm'
);

$summary = array();
foreach ($openHours as $day => $hours) {
    if (!array_key_exists($hours, $summary))
        $summary[$hours] = array($day);
    else
        $summary[$hours][] = $day;
}

foreach ($summary as $hours => $days) {
    echo array_shift($days) . '-' . array_pop($days) . ' ' . $hours . PHP_EOL;
}

Upvotes: 1

Views: 205

Answers (2)

Rizier123
Rizier123

Reputation: 59681

This should work for you:

First we change the array structure and use the time as key and the days as values with this code:

foreach($openHours as $k => $v)
    $array[$v][] = $k;

So we end up with an array structure like this:

Array
(
    [9am-7pm] => Array
        (
            [0] => Mon
            [1] => Wed
            [2] => Fri
            [3] => Sun
        )

    [9am-10pm] => Array
        (
            [0] => Tue
            [1] => Thu
            [2] => Sat
        )

)

After that we just need to loop through the new array and implode() the days to a string separated by a comma and append the time after it.

Code:

<?php

    $openHours = array(
        'Mon' => '9am-7pm',
        'Tue' => '9am-10pm',
        'Wed' => '9am-7pm',
        'Thu' => '9am-10pm',
        'Fri' => '9am-7pm',
        'Sat' => '9am-10pm',
        'Sun' => '9am-7pm'
    );


    foreach($openHours as $k => $v)
        $array[$v][] = $k;

    foreach($array as $time => $days)
        echo implode(",", $days) . " " . $time . PHP_EOL;

?>

output:

Mon,Wed,Fri,Sun 9am-7pm
Tue,Thu,Sat 9am-10pm

Upvotes: 1

Horaland
Horaland

Reputation: 897

$closetime = ['7:00'=>['Mon','Wed','Fri','Sun'], '10:00'=>['Tue','Thu','Sat']];

foreach ($closetime as $time => $days) { echo explode(',', $days)." - 9:00 - ".$time; }

or something like that

Upvotes: -2

Related Questions