tags:

views:

38

answers:

2

Hi All,

Im wanting to organize a series of dates in the following format. As a bit of context, the dates are the dates of upcoming events that can be added by my users. The format:

January 2011

date - event

date - event

date - event

February 2011

date - event

date - event

date - event

with all events in a given month, arranged by the date on which they occur. All of my event dates are stored in my database as unix timestamps. Problem is, i dotn know where id start to develop a function that would order all of my events in this way. Can anyone help me out?

Cheers

+2  A: 

Iterate the events; keep track of the last MONTH seen. If the current month != previous month, display a month separator.

$lastDate = '';

foreach ($events as $e)
{   
    $currDate = date('F Y', $e->date);
    if ($currDate != $lastDate )
    {
        echo "<h1>$currDate</h1>";
    }
    // might want to format the date to be human readable here...
    echo "<li>$e->date, $e->event"; 
    $lastDate = $currDate;

}
Byron Whitlock
That does assume the events are already in chronological order, which would be the case if you were ordering by the timestamp in the SQL query. If you were simply leaving the results sorted by ID or some other criteria, this code wouldn't work as intended.
Geoff Adams
+4  A: 

I like to group the items first using an array index.

Controller

$months = array();
foreach ($rows as $row) {
    $month = date('F Y', strtotime($row['date']);

    if (!isset($months[$month]) {
        $months[$month] = array();
    }

    $months[$month][] = $row;
}

View

foreach ($months as $month => $events) {
    echo '<h2>' . $month . '</h2>';
    foreach ($events as $event) {
        // ...
    }
}
Philippe Gerber
+1 that is clean and takes advantage php's array handling.
Byron Whitlock
Modified version of this, but on the same principal, worked a treat. Cheers.
richzilla