我有以下代码,这些代码在过去的一周内持续了52周。我想修改它以便它只包括当前年份。所以它应该只显示1月的前4周。
public static function weeks()
{
$nextWeek = strtotime('+1 week');
for($i=0;$i<52;$i++)
{
$date = date('Y-m-d', strtotime('-'.$i.' week'));
$nbDay = date('N', strtotime($date));
$monday = new \DateTime($date);
$sunday = new \DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
if($nextWeek > strtotime($sunday->format('Y-m-d'))) {
$weeks[$monday->format('W')] = $monday->format('j M Y') . ' - ' . $sunday->format('j M Y');
}
}
return $weeks;
}
如何修改代码?
答案 0 :(得分:2)
你可以使用date()
和W
一年中的一周作为循环的上限吗?
public static function weeks()
{
$nextWeek = strtotime('+1 week');
/* change the upper bound of the loop using `date('W')` */
for( $i=0; $i < date('W'); $i++ )
{
$date = date('Y-m-d', strtotime('-'.$i.' week'));
$nbDay = date('N', strtotime($date));
$monday = new \DateTime($date);
$sunday = new \DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
if($nextWeek > strtotime($sunday->format('Y-m-d'))) {
$weeks[$monday->format('W')] = $monday->format('j M Y') . ' - ' . $sunday->format('j M Y');
}
}
return $weeks;
}