[Drupal] Help adding date wrappers around events with certain dates

Hi all

I’m trying to add some logic to my existing Drupal php code which display some events.

I have a number of Drupal nodes (events) all with a date usually spanning over a one day period, example - Monday 8pm to Tuesday 3am. These events are being displayed as a big list or set LIMIT depending on the page.

I currently have a foreach loop inside a EntityFieldQuery which displays all events.

This is generally the bulk of the code

$nodes = array();

  if(isset($result['node'])) {
    $ids = array_keys($result['node']);
    $nodes = entity_load('node',$ids);
  }

  $build = array(
    '#prefix'=> '<div><ul>',
    '#suffix'=> '</ul></div>',
  );

  foreach($nodes as $node) {

    $build['node_'.$node->nid] = array(
      '#prefix'=> '<li>',
      '#suffix'=> '</li>',
    );

    $build['node_'.$node->nid]['field_event_date_and_time'] = array(
      '#type'=> 'markup',
      '#markup'=> '<strong>When:</strong> ' . date("g:ia", strtotime($node->field_event_date_and_time['und'][0]['value'])),
      '#prefix'=> '<div>',
      '#suffix'=> '</div>',
      '#weight'=> 1,
    );
...  

And with the above I get results like:

March 2014
Event 1
March 2014
Event 2
March 2014
Event 3

Monday 17th March 2014
Event 1
Monday 17th March 2014
Event 2
Monday 17th March 2014
Event 3

I now need a month title to group some of these events and a day title to group others.
I need to show the date header only once for a whole group of events, not for every event on the same day/month.

I need to produce something like:

March 2014
Event 1
Event 2
Event 3

April 2014
Event 1
Event 2
Event 3

and so on…

And also have the option to do things by the day

Monday 17th March 2014
Event 1
Event 2
Event 3

Tuesday 18th March 2014
Event 1
Event 2
Event 3

I’d like to place the title inside a <li> to continue the list if possible.
Can anybody help?

I think something along these lines

get datetime
do we have any events with this date
yes

  • print date once
  • loop and print events below
    no
  • move onto next day/month and repeat

Thank you,
Barry