View Full Version : Displaying consecutive days with non-consecutive days.
11-08-2010, 04:02 PM
Ok, I think I'm having a Monday morning brain fart here. I know there's a simple solution that I'm missing. Here's the situation...
I'm reading days open for a store location in the database and placing that data into an array that ends up like this...
$days_open = array(
$days_closed = array(
I want to display...
Open: Mon, Thurs-Sat
Closed: Sun, Tue-Thurs
I've tried a few different approaches, but nothing seems to work for all the various combinations.
PS: Assuming Sunday is the start day of the week
11-08-2010, 04:26 PM
You could assign keys to the arrays, representing the day of the week, and as you foreach, check if the last key and the current key are consecutive, and if the current key is the last key. If it is consecutive and not the last, skip it, and if it is the last, put it in.
11-08-2010, 05:29 PM
Here's a hackish way of doing it:
function days_concat( Array $days )
// Define all days of the week
static $all_days = array(
'Sun', 'Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat'
// prepare our output
$output = array();
// loop through all days of the week
foreach ( $all_days as $i => $day )
// if it is included, grab it
if ( in_array( $day, $days ) )
$output = $day;
// ...otherwise, mark it with a hash
$output = '#';
// clean everything up
$output = implode( '#', $output );
$output = trim( $output, '#' );
// two or more consecutive hashes = days that are two or more apart
$output = preg_split( '/##+/', $output, NULL, PREG_SPLIT_NO_EMPTY );
// turn consecutive days into dashed days
foreach ( $output as $i => $value )
$output[ $i ] = preg_replace( '/#(\w+#)*/', '-', $value );
// format with commas
$output = implode( ', ', $output );
// send it on it's way!
// Mon, Thurs
echo days_concat( array( 'Mon', 'Thurs' ) );
// Mon, Wed-Thurs
echo days_concat( array( 'Mon', 'Wed', 'Thurs' ) );
// Mon, Wed-Fri
echo days_concat( array( 'Mon', 'Wed', 'Thurs', 'Fri' ) );
// Sun-Tue, Thurs-Sat
echo days_concat( array( 'Sun', 'Mon', 'Tue', 'Thurs', 'Fri', 'Sat' ) );
...eh, get's the job done.
11-08-2010, 09:43 PM
Thanks. Seems to do the trick.
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.