1

I currently have this code:

$dates = array();
foreach($data['sc_event_dates'] as $date) {
    if($date > time()) {
        $dates[] = date( empty($dates) ? "D d M": "d M", $date);
    }
}
echo implode(", ", $dates);

And it displays something like this:

Thu 11 Aug, 18 Aug, 25 Aug, 01 Sep, 08 Sep, 15 Sep

But what I need to do group the dates of each month so the output would look like this:

Thu 11, 18, 25 Aug, 01, 08, 15 Sep

$data['sc_event_dates'] holds an array of unix timestamps and is ordered in ascending order.

Also dates that are before current time need to be ignored.

Here is some example data:

Array
(
    [0] => 1313020800
    [1] => 1313625600
    [2] => 1314230400
    [3] => 1314835200
    [4] => 1315440000
    [5] => 1316044800
)

Can any one help alter my code, or produce new code, to get my desired output?

2 Answers 2

1
$dates = array();
foreach($data['sc_event_dates'] as $key => $date) {
    if($date > time()) {

        $next = ++$key;
        $format = 'd';

        if( empty($dates) ) {

            $format = 'D '.$format;
        }

        if( !isset( $data['sc_event_dates'][$next] ) || date('n', $date) != date('n', $data['sc_event_dates'][$next]) ) {

            $format .= ' M';
        }

        $dates[] = date( $format, $date);
    }
}
echo implode(", ", $dates);
Sign up to request clarification or add additional context in comments.

Comments

0

You'd a simple state machine to keep track of which month is being displayed and adjust output as need be.

$prev_month = null;
foreach(... as $date) {
   if ($date < time()) {
      continue;
   }
   $day = date('D', $date);
   $day_num = date('d', $date);
   $month = date('M');
   if ($prev_month != $month) {
       echo $month, ' ';
       $prev_month = $month;
       $sep = '';
   }
   echo $day_num, $sep;
   $sep = ', ';
}

not tested, YMMV, etc...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.