我有一个脚本,我需要在(星期一到星期四)和(星期五到星期日)分开几个月。
我正在使用一个函数来创建一个范围内所有日期的数组,然后遍历该数组以分隔日期。
function createDateRangeArray($strDateFrom,$strDateTo){
$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)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
$date = "2013-07-01";
$end_date = "2013-07-31";
$date_range = createDateRangeArray($date, $end_date);
$final_array = array();
$temp_array = array();
foreach ($date_range as $value) {
$temp_array[] = $value;
$day_of_week = date("N", strtotime($value));
if ($day_of_week == 4 || $day_of_week == 7) {
$final_array[] = $temp_array;
$temp_array = array();
}
}
当我执行print_r($ date_range)时,我得到:
Array
(
[0] => 2013-07-01
[1] => 2013-07-02
[2] => 2013-07-03
[3] => 2013-07-04
[4] => 2013-07-05
[5] => 2013-07-06
[6] => 2013-07-07
[7] => 2013-07-08
[8] => 2013-07-09
[9] => 2013-07-10
[10] => 2013-07-11
[11] => 2013-07-12
[12] => 2013-07-13
[13] => 2013-07-14
[14] => 2013-07-15
[15] => 2013-07-16
[16] => 2013-07-17
[17] => 2013-07-18
[18] => 2013-07-19
[19] => 2013-07-20
[20] => 2013-07-21
[21] => 2013-07-22
[22] => 2013-07-23
[23] => 2013-07-24
[24] => 2013-07-25
[25] => 2013-07-26
[26] => 2013-07-27
[27] => 2013-07-28
[28] => 2013-07-29
[29] => 2013-07-30
[30] => 2013-07-31
)
然而,当我在上面的foreach循环中运行它时,除了本月的最后几天之外它会抓住所有内容。如果我运行print_r($ final_array),我会得到这个:
Array
(
[0] => Array
(
[0] => 2013-07-01
[1] => 2013-07-02
[2] => 2013-07-03
[3] => 2013-07-04
)
[1] => Array
(
[0] => 2013-07-05
[1] => 2013-07-06
[2] => 2013-07-07
)
[2] => Array
(
[0] => 2013-07-08
[1] => 2013-07-09
[2] => 2013-07-10
[3] => 2013-07-11
)
[3] => Array
(
[0] => 2013-07-12
[1] => 2013-07-13
[2] => 2013-07-14
)
[4] => Array
(
[0] => 2013-07-15
[1] => 2013-07-16
[2] => 2013-07-17
[3] => 2013-07-18
)
[5] => Array
(
[0] => 2013-07-19
[1] => 2013-07-20
[2] => 2013-07-21
)
[6] => Array
(
[0] => 2013-07-22
[1] => 2013-07-23
[2] => 2013-07-24
[3] => 2013-07-25
)
[7] => Array
(
[0] => 2013-07-26
[1] => 2013-07-27
[2] => 2013-07-28
)
)
甚至更奇怪的是,当我将日期范围更改为(2013-06-01至2013-06-30)或(2013-08-01至2013-08-31)时,它会将所有日期更改为$ final_array应该是这样的方式。
答案 0 :(得分:2)
我的思维过程是您错过了重新添加$temp_array
的最后一步,因为您没有完全达到4
或7
标记。它适用于其他日期,因为星期几设置得很好。
尝试通过在foreach之后添加数组(如果不为空)来确认:
foreach ($date_range as $value) {
$temp_array[] = $value;
$day_of_week = date("N", strtotime($value));
if ($day_of_week == 4 || $day_of_week == 7) {
$final_array[] = $temp_array;
$temp_array = array();
}
}
if ( count( $temp_array ) > 0 ){ // anything leftover?
$final_array[] = $temp_array; // append to $final_array
}