在php中从数组中计算范围日期之间的周末天数
我试图从下面的数组中计算日期之间的周末天数:在php中从数组中计算范围日期之间的周末天数,php,symfony,Php,Symfony,我试图从下面的数组中计算日期之间的周末天数: $dates[] = array ( 'DateFrom' => '2015-07-10', 'DateTo' => '2015-07-10', 'DateFrom' => '2015-07-12', 'DateTo' => '2015-07-12', 'DateFrom'=> '2015-07-17', 'DateTo'=> '2015-07-19') ; 结果必须返回这些日期之间的周末天数 这些日期之间
$dates[] = array ( 'DateFrom' => '2015-07-10', 'DateTo' => '2015-07-10', 'DateFrom' => '2015-07-12', 'DateTo' => '2015-07-12', 'DateFrom'=> '2015-07-17', 'DateTo'=> '2015-07-19') ;
结果必须返回这些日期之间的周末天数
这些日期之间是3天的周末(2015-07-12、2015-07-18和2015-07-19)
有人知道吗?您需要从开始日期循环到结束日期,并且在每次迭代中需要检查日期(周六/周日) 算法:
$weekends=0;
$startDate=strottime($startDate);
$endDate=strottime($endDate);
虽然($startDate首先,如果您完全按照写入的方式定义数组,那么您将复制键,其中四个项将被覆盖。但假设我们只是查看这些对。将每对中的FromDate和ToDate传递到此函数,并将所有返回值相加
function getWeekends ($fromDate, $toDate) {
$from = strtotime($fromDate);
$to = strtotime($toDate);
$diff = floor(abs($to-$from)/(60*60*24)); // total days betwixt
$num = floor($diff/7) * 2; // number of weeks * 2
$fromNum = date("N", $from);
$toNum = date("N", $to);
if ($toNum < $fromNum)
$toNum += 7;
// get range of day numbers
$dayarr = range($fromNum, $toNum);
// check if there are any weekdays in that range
$num += count(array_intersect($dayarr, array(6, 7, 13)));
return $num;
}
函数getWeekends($fromDate,$toDate){
$from=STROTIME($fromDate);
$to=标准时间($toDate);
$diff=楼层(abs($to-$from)/(60*60*24));//间隔的总天数
$num=floor($diff/7)*2;//周数*2
$fromNum=日期(“N”,$from);
$toNum=日期(“N”,至美元);
如果($toNum<$fromNum)
$toNum+=7;
//获取日数的范围
$dayarr=范围($fromNum,$toNum);
//检查该范围内是否有工作日
$num+=count(数组相交($dayarr,数组(6,7,13));
返回$num;
}
可能会有更优雅的解决方案。在每对日期上使用:
function getWeekendDays($startDate, $endDate)
{
$weekendDays = array(6, 7);
$period = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1D'),
new DateTime($endDate)
);
$weekendDaysCount = 0;
foreach ($period as $day) {
if (in_array($day->format('N'), $weekendDays)) {
$weekendDaysCount++;
}
}
return $weekendDaysCount;
}
在PHP中,您不能在关联数组中重复该键。您可以创建多维数组来容纳日期。请先重新编写代码,并注意缩进以提高可读性。此外,您还需要将输入数组格式化为多维数组。
function getWeekendDays($startDate, $endDate)
{
$weekendDays = array(6, 7);
$period = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1D'),
new DateTime($endDate)
);
$weekendDaysCount = 0;
foreach ($period as $day) {
if (in_array($day->format('N'), $weekendDays)) {
$weekendDaysCount++;
}
}
return $weekendDaysCount;
}