Combine days where opening hours are similar

前端 未结 2 1184
Happy的楠姐
Happy的楠姐 2020-12-14 04:15

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

Mon 9am-5pm
Tue          


        
相关标签:
2条回答
  • 2020-12-14 04:38
    <?php
    $openHours = array(
        'Mon' => '9am-5pm',
        'Tue' => '9am-5pm',
        'Wed' => '9am-9pm',
        'Thu' => '9am-5pm',
        'Fri' => '9am-5pm',
        'Sat' => '9am-7pm',
        'Sun' => '9am-7pm'
    );
    
    $summaries = array();
    foreach ($openHours as $day => $hours) {
        if (count($summaries) === 0) {
            $current = false;
        } else {
            $current = &$summaries[count($summaries) - 1];
        }
        if ($current === false || $current['hours'] !== $hours) {
            $summaries[] = array('hours' => $hours, 'days' => array($day));
        } else {
            $current['days'][] = $day;
        }
    }
    
    foreach ($summaries as $summary) {
        if (count($summary['days']) === 1) {
            echo reset($summary['days']) . ' ' . $summary['hours'] . PHP_EOL;
        } else {
            echo reset($summary['days']) . '-' . end($summary['days']) . ' ' . $summary['hours'] . PHP_EOL;
        }
    }
    

    codepad sample

    0 讨论(0)
  • 2020-12-14 04:59

    If you want it in the following format:

    Sun-Tue, Fri-Sat: 11am-12am; Wed: 10am-12am; Thu: 9am-12am

    Which will group days and handle different times within the week:

    <?php
    $open_hours = array (
        "Sun" => "11am-12am",
        "Mon" => "11am-12am",
        "Tue" =>  "11am-12am",
        "Wed" =>  "10am-12am",
        "Thu" =>  "9am-12am",
        "Fri" =>  "11am-12am",
        "Sat" =>  "11am-12am"
    );
    
    $result = [];
    foreach ($open_hours as $day => $hours) {
        if (empty($result) || $previous !== $hours) {
            $result[$hours][] = $day;
        } elseif ($previous === $hours) {
            $key = array_key_last($result[$hours]);
            $current = strtok($result[$hours][$key], '-');
            $result[$hours][$key] = $current.'-'.$day;
        }
        $previous = $hours;
    }
    
    // build output (joining days with ,)
    $output = [];
    foreach ($result as $hours => $days) {
        $output[] = implode(', ', $days).': '.$hours;
    }
    // join with ;'s and output
    echo implode('; ', $output);
    

    https://3v4l.org/tKOlI

    0 讨论(0)
提交回复
热议问题