I have an array like:
array(
['march'] => array(
'2', '3', '4', '5', '6', '23', '24', '25', '30'
);
);
I need to convert that into:
03/02/2012 - 03/06/2012
03/23/2012 - 03/25/2012
03/30/2012
I have an array like:
array(
['march'] => array(
'2', '3', '4', '5', '6', '23', '24', '25', '30'
);
);
I need to convert that into:
03/02/2012 - 03/06/2012
03/23/2012 - 03/25/2012
03/30/2012
You can find the consecutive timespans by looping through your array like so:
$months = array(
'march' => array(
'2', '3', '4', '5', '6', '23', '24', '25', '30'
)
);
$current_day = 0;
$span_start = 0;
$span_end = 0;
foreach($months['march'] as $day) {
if ($day > ++$current_day) {
$current_day = $day;
if ($span_start) {
// print it out:
echo "$span_start..$span_end\n";
}
$span_start = $day;
}
$span_end = $day;
}
// print the last one:
echo "$span_start..$span_end";
Output: (Demo)
2..6
23..25
30..30
For formatting/parsing/printing the dates, however, others' suggestion to use the built in time and date functions are absolutely correct.
My solution below will pre-define the year to accompany your date data for consistency. Although you only have one month listed, I'll design the script with the intent to handle multiple months.
Use nested loops to iterate over your input data. Keep track of the previously encountered day number to determine if hyphenation is needed. Push reference elements into the result and extend those references until a non-consecutive day is encountered.
Code: (Demo)
function rangify(array $daysByMonth, $y = '2012'): string {
$result = [];
foreach ($daysByMonth as $m => $days) {
$lastD = null;
foreach ($days as $d) {
if (($d - 1) == $lastD) {
$ref = preg_replace('/ -[^-]+$/', '', $ref) . date(' - m/d/Y', strtotime("$d $m $y"));
} else {
unset($ref);
$ref = date('m/d/Y', strtotime("$d $m $y"));
$result[] =& $ref;
}
$lastD = $d;
}
}
return implode("\n", $result);
}
$months = [
'march' => [
'2', '3', '4', '5', '6', '23', '24', '25', '30'
],
'june' => [
'3', '4', '5'
]
];
echo rangify($months);
Output:
03/02/2012 - 03/06/2012
03/23/2012 - 03/25/2012
03/30/2012
06/03/2012 - 06/05/2012
$array = array(
'2', '3', '4', '5', '6', '23', '24', '25', '30'
);
foreach($array as $date){
echo '03/'.$date.'/2012;
}
You may need to add a zero before single unit dates!