Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 9am-5pm
Wed 9am-5pm
Thu 9am-5pm
Fri 9am-5pm
Sat 9am-7pm
Sun 9am-7pm

I want the code to simplify it to:

Mon-Fri 9am-5pm
Sat-Sun 9am-7pm

How do I do this without a long list of if/else or case ifs? I'm using CodeIgniter..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
454 views
Welcome To Ask or Share your Answers For Others

1 Answer

<?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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...