I have this function to generate an array of dates between a range. I need to modify it so that it will accept another paramerter if passed with a particular day of the week.
I will then get all the dates for that day within the range. I have not been able to modify. Thanks.
Here is my updated code, it is still add for evey day in the date range even though I am passing in the value of 6. I is probably staring me in the face but I cannot see it.
function createDateRangeArray开发者_StackOverflow中文版($strDateFrom,$strDateTo,$dateOfWeek=6) {
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2),substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom) {
if(!isset($dateOfWeek) || date('w')==$dateOfWeek) //if dateOfWeek not given or same as given
array_push($aryRange,date('Y-m-d',$iDateFrom));
while ($iDateFrom<$iDateTo) {
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
if(count($aryRange)<1){
return false;
} else{
return $aryRange;
}
}
replace
array_push($aryRange,date('Y-m-d',$iDateFrom));
by
if(date('w',$iDateFrom)==$dateOfWeek)
array_push($aryRange,date('Y-m-d',$iDateFrom));
where $dateOfWeek
is 0 (for Sunday) through 6 (for Saturday)
Besides, you can rewrite your code to:
while ($iDateFrom<$iDateTo) {
array_push($aryRange,date('Y-m-d',$iDateFrom));
$iDateFrom+=86400; // add 24 hours, after adding it
}
to avoid repeat of code here (You need not if
after that)
To add it as optional argument:
function createDateRangeArray($strDateFrom,$strDateTo,$dateOfWeek=null){
if(!isset($dateOfWeek) || date('w')==$dateOfWeek) //if dateOfWeek not given or same as given
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
The above answer (from RiaD) basically nails it.
Just a note: if you want just a specific weekday, there's no need to iterate every weekday.
You could iterate everyday until the first desired weekday, from them on just skip 86400*7 seconds. Much more efficient.
精彩评论