在循环中插入每周的计划

时间:2011-08-15 10:33:40

标签: php mysql

我已使用listmailpro设置了计划电子邮件脚本。我需要安排在接下来的几年中每月的每个星期一发送一封电子邮件。下面的例子显示了我想要实现的目标。我怎么能写一个快速的PHP脚本来为我插入日程表,更改每个插入的日期?

INSERT INTO `lm_schedule` (`id`, `type`, `date`, `subject`, `message`, `htmessage`, `fattach`, `list`) VALUES
('', 'm', '2011-08-15', 'Test weekly email (!date2)', 'email text', 'email body', '', '1'),
('', 'm', '2011-08-22', 'Test weekly email (!date2)', 'email text', 'email body', '', '1'),
('', 'm', '2011-08-29', 'Test weekly email (!date2)', 'email text', 'email body', '', '1'),
('', 'm', '2011-09-05', 'Test weekly email (!date2)', 'email text', 'email body', '', '1');

3 个答案:

答案 0 :(得分:1)

$date = new DateTime('Monday'); // today or next monday
$end = new DateTime('now + 10 years');

// for each monday between now and the next 10 years, insert a schedule
while ($date < $end) {
    insert_schedule($date);
    $date->modify('next Monday');
}

或者以命令式的方式:

$date = date_create('Monday'); // today or next monday
$end = date_create('now + 10 years');

// for each monday between now and the next 10 years, insert a schedule
while ($date < $end) {
    insert_schedule($date);
    date_modify($date, 'next Monday');
}

答案 1 :(得分:1)

未经测试但应该给出一个粗略的想法:

$init = strtotime('2011-08-15');
$stop = strtotime('2013-08-15');
$step = 604800;

switch (date('w', $init)) {
    case 0:
        $correction = 1;
        break;
    case 1:
        $correction = 0;
        break;
    case 2:
        $correction = 6;
        break;
    case 3:
        $correction = 5;
        break;
    case 4:
        $correction = 4;
        break;
    case 5:
        $correction = 3;
        break;
    case 6:
        $correction = 2;
        break;
}
$init += $correction * $step;

$qry = 'INSERT INTO `lm_schedule` (`id`, `type`, `date`, `subject`, `message`, `htmessage`, `fattach`, `list`) VALUES (';
$dates = array();

for ($timestamp = $init; $timestamp < $stop; $timestamp += $step) {
    $dates[] = ' ... ' . date('Y-m-d', $timestamp) . ' ... ';
}

$qry .= implode('),(', $dates) . ');';

答案 2 :(得分:0)

试试这个......

<?php

  $startdate = '2011-08-15';
  $numweeks = 104; // 2 years (52 x 2)

  $oneweek = 60 * 60 * 24 * 7; // length of 1 week in seconds
  $currenttime = strtotime($startdate); // Unix timestamp of start date

  for ($i = 0; $i < $numweeks; $i++) {
    $thisdate = date('Y-m-d',$currenttime);
    mysql_query("INSERT INTO `lm_schedule` (`id`, `type`, `date`, `subject`, `message`, `htmessage`, `fattach`, `list`) VALUES ('', 'm', '$thisdate', 'Test weekly email (!date2)', 'email text', 'email body', '', '1')");
    $thisdate += $oneweek;
  }

?>