NYCPHP Meetup

NYPHP.org

[nycphp-talk] store's opening hours

David Sklar sklar at sklar.com
Thu Oct 2 15:42:03 EDT 2003


On Thursday, October 02, 2003 2:59 PM,  wrote:

> I've got a stumper.. or at least it is over here.. and I've been
> looking for a solution.
>
> For each day of the week, I have an opening time and closing time for
> a store.  If the opening and closing times are the same for
> sequential days, I would like to display the days as a range.  For
> example:
>
> Mon-Fri 10:00 to 7:00
> Sat-Sun 11:00 to 5:00
>
> Does anybody have any ideas?  Resources?  Philosophies?

How about something like the code below? It's the same kind of logic you use
when you're printing out a list of date-sorted items and you want a new
header only when the day changes, e.g. something like

October 1
---------
10:00 Get Haircut
12:00 Eat Lunch

October 2
---------
12:00 Eat Lunch

The idea is that while iterating through your items, you keep track of the
relevant attribute (day) of the current item and compare it to the attribute
of the previous or next item. If the two are different, then it's time to
print a header (or a listing of hours).

David
----------------
$open_close = array('Mon' => array('10:00','4:00'),
                    'Tue' => array('10:00','4:00'),
                    'Wed' => array('10:00','3:30'),
                    'Thu' => array('10:00','4:00'),
                    'Fri' => array('10:00','4:00'),
                    'Sat' => array('9:00','5:00'),
                    'Sun' => array('9:00','5:00'));

$days = array_keys($open_close);
// The first line of hours starts with the first day
$first_day = $days[0];
for ($i = 0, $j = count($open_close); $i < $j; $i++) {
    // What's the name of the current day?
    $today = $days[$i];
    if (($i == ($j - 1)) || // Is this the last day?
        (($tomorrow = $days[$i+1]) &&  // What's the name of tomorrow?
         // Does tomorrow open at a different time than today?
         (($open_close[$today][0] != $open_close[$tomorrow][0]) ||
          // Does tomorrow close at a different time than today?
          ($open_close[$today][1] != $open_close[$tomorrow][1])))) {

        // If it's the last day, or tomorrow's times are different
        // than today's times, then report the times for
        // $first_day to $today
        printf("%s%s %4s to %4s\n",
               // Don't print "Mon-Mon", just print "Mon";
               ($first_day == $today) ? '    ' : $first_day.'-',
               $today,
               $open_close[$today][0],
               $open_close[$today][1]);
        // The next line of output starts with tomorrow
        $first_day = $tomorrow;
    }
}




More information about the talk mailing list