繁体   English   中英

插入从本周开始的年度 rest 记录

[英]Insert records for the rest of the year starting on current week

我正在尝试为当年的 rest 插入相同的记录。

由于我们目前处于 2021 年的第 13 周,总共还有 40 周(包括第 13 周)。

使用以下代码,我可以获得当前年份和星期:

define('NL', "\n");

$ddate = date("Y/m/d");
$date = new DateTime($ddate);
$currentyear = $date->format("Y");
$week = $date->format("W");

echo "Current Year: $currentyear", NL;
echo "Weeknumber: $week", NL;

以上将output如下:

Current Year: 2021
Weeknumber: 13

这是我尝试使用 WHILE 循环创建具有不同周数的 INSERT 查询:

$year  = $currentyear;

$firstDayOfYear = mktime(0, 0, 0, 1, 1, $year);
$nextSunday     = strtotime('monday', $firstDayOfYear);

while (date('Y', $nextSunday) == $year) {
  $insert = "INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES ($nextSunday, $year', NOW(), 'jbeasley')";
  
  echo $insert, NL;

  $nextSunday = strtotime('+1 week', $nextSunday);
}

这是 output 的外观:

 INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES (1, '2021', NOW(), 'jbeasley')
 INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES (2, '2021', NOW(), 'jbeasley')
 INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES (3, '2021', NOW(), 'jbeasley')
 // and so on up to 52 (there are 52 weeks in 2021)

这在很大程度上是有效的,但这也是我卡住的地方。

我不确定如何让 INSERT 在本周开始,不管之前的所有星期。 在这种情况下,由于我们目前处于第 13 周,因此第一个 INSERT 应该从第 13 周开始,然后是剩余的几周,如下所示:

INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES (13, '2021', NOW(), 'jbeasley')
INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES (14, '2021', NOW(), 'jbeasley')
INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES (15, '2021', NOW(), 'jbeasley')
// and so on until the final week

使用 El_Vanja 的建议,我更新了 WHILE 循环以包含一个 IF/ELSE 来检查当前周是否大于:

while (date('Y', $nextSunday) == $year) {
  if($week > date('W', $nextSunday)){
    echo "skip this week " . date('W', $nextSunday), NL;
    $nextSunday = strtotime('+1 week', $nextSunday);
  }
  else{
    $insert = "INSERT INTO history (`WEEK`, `YEAR`, `ADDDATE`, `USERNAME`) VALUES ($nextSunday, $year, NOW(), 'jbeasley')";

    echo $insert, NL;

    echo date('W', $nextSunday), NL;
    $nextSunday = strtotime('+1 week', $nextSunday);
  }
}

使用上述方法,循环将跳过过去几周,仅在当前周开始创建查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM