Show PHP array of UNIX timestamps as string in a particular format
I currently have this cod开发者_如何学Ce:
$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?
$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);
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...
精彩评论