Main
Index
Search
Posts
Who's
Online
Log
In

Home: Products: CMS Builder:
Group By date

 

 


terryally
User

Dec 19, 2011, 4:21 AM

Post #1 of 3 (384 views)
Shortcut
Group By date Can't Post

Hi,

I have a listing of shows which may spread over 12 or more months.

I currently have them grouped by month but I need them grouped by month AND year.

The current listing is by calendar order but I want a chronological order i.e.

Rather than:

Jan (2012)
Feb (2012)
Mar (2012)
... continuing to...
Nov (2012)
Dec (2011)

I would like:

Dec (2011)
Jan (2012)
Feb (2012)
Mar (2012)
Nov (2012)
Dec (2012)

Is there a way to get this done?

The code I currently use to create each month's listing is:


Code
				<!-- ********* JANUARY ********* --> 
<?php
list($showsRecords, $showsMetaData) = getRecords(array(
'tableName' => 'shows',
'where' => 'start_date >= NOW() AND MONTH(start_date) = 1',
'orderBy' => 'start_date ASC',
));
$showsRecord = @$showsRecords[0]; // get first record
?>


<!-- ********* FEBRUARY ********* -->
<?php
list($showsRecords, $showsMetaData) = getRecords(array(
'tableName' => 'shows',
'where' => 'start_date >= NOW() AND MONTH(start_date) = 2',
'orderBy' => 'start_date ASC',
));
$showsRecord = @$showsRecords[0]; // get first record
?>


etc etc


Thanks
Terry


Jason
Staff / Moderator


Dec 19, 2011, 8:29 AM

Post #2 of 3 (379 views)
Shortcut
Re: [terryally] Group By date [In reply to] Can't Post

Hi Terry,

Try this, you may find this approach easier.

Instead of having a separate query for each month, select all the records in one query, then organize them by month/year like this:


Code
list($showsRecords, $showsMetaData) = getRecords(array(  
'tableName' => 'shows',
'where' => 'start_date >= NOW()',
'orderBy' => 'start_date ASC',
));

$showsByDate = array();

foreach ($showsRecords as $show) {
$dateHeader = date("M (Y)", strtotime($show['start_date']));

if (!array_key_exists($header, $showsByDate)) {
$showsByDate[$dateHeader] = array();
}

$showsByDate[$dateHeader][] = $show;
}


At the end of this code, the variable $showsByDate will have all of your show records, organized by a month/year header.

You can then output this by using two foreach loops like this:


Code
<?php foreach ($showsByDate as $header => $shows): ?> 
<?php echo $header; ?>

<?php foreach ($shows as $show): ?>
// output show information here
<?php endforeach ?>
<?php endforeach ?>


Hope this helps get you started.
---------------------------------------------------
Jason Sauchuk - Programmer 
interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/ 


terryally
User

Dec 23, 2011, 5:22 AM

Post #3 of 3 (370 views)
Shortcut
Re: [Jason] Group By date [In reply to] Can't Post

Hello Jason,

This lists them exactly how I wanted.

Thank you very much.

Best wishes for Christmas and 2012 to you, Dave and all other colleagues at InteractiveTools.com.

Terry