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开发者_JAVA技巧 this without a long list of if/else or case ifs? I'm using CodeIgniter..
<?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
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
精彩评论