views:

163

answers:

4

Hi,

I am working on a php program that needs to store many "Event" objects in an array. Each event has a "due" date, and I need to be able to easily get these events by that day. There may be more than one event on any given day.

I thought about using a MySQL-style date as the key, like $array["year-month-day"], but it's messy. I also tried $array[year][month][day], but then I get a 4d array, which also seems messy to me.

My question is this: Has anyone found a good way of storing objects by time like this, and if so, how did you do it?

A: 

Encode the date as a day of the year instead? (i.e. 1-365, or 0-364 if you prefer)

If you have a time value (from strtotime() or whatever), you can easily get the day-of-year by using date('z', $time) which returns a value from 0-365 (365 for a leap day).

You could then use something like $events[year][day][index] which reduces your nesting by one level - honestly, nesting isn't "the devil" or anything, as long as it doesn't go too far.

Amber
A: 

You could use a timestamp. Note that on any system using a signed 32-bit integer as the underlying timestamp type, your app will suffer from the year 2038 problem.

outis
Or `timestamp` % 86400, to facilitate retrieval by day. And postpone the better solution some 30 years ;-)
Michael Krelin - hacker
`timestamp % 86400` is time-of-day.
outis
+2  A: 

What's wrong with $array['2009-08-20'][0], $array['2009-08-20'][1], et cetera? That doesn't seem at all "messy," given the structure of the data you're hoping to represent.

If you wanted to also access events by year and by month, the 4D structure you describe might make more sense (or an entirely different structure), but when "day" is your principle organization, go with a simple (and human-readable) depiction of dates like you described for the array index.

VoteyDisciple
I might need year and month access at some point; I am hoping to find an open-ended solution.
Travis G.
Also, assuming I do use a 4d array, what is the best way to initialize the many array levels and avoid invalid keys?
Travis G.
A: 

Store an array keyed by Unix time at 12:00:00am on that day. That array will contain all events for that day.

It's easy to convert between Unix time and human-readable dates using PHP's strtotime(), time(), and date() functions.

Lucas Oman
Is 12:00:00 am the standardized way to store a timestamp of a day?
Travis G.
I'm not sure if it's sanctioned by a standards organization (or needs to be), but zeroing the time (12am is 00:00:00 in military time) makes sense to me. I often use this scheme in my code.
Lucas Oman