结合开放时间相似的日子

时间:2011-05-06 05:03:32

标签: php codeigniter

我如何在PHP中编写一个函数(使用CodeIgniter)来合并具有类似商店营业时间的日子。例如,如果我们有:

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

我希望代码将其简化为:

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

如果没有if / else或case ifs的长列表,我该怎么做?我正在使用CodeIgniter ..

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:0)

如果要使用以下格式:

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

哪些人将对天进行分组并在一周内处理不同的时间?

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