Php 计算每个阵列的开始和结束日期?
我有一个单词数组,从那天下午5点到第二天下午5点,每个单词都是有效的,然后下一个单词就是有效的周末除外在周末,星期五的一个词持续到星期一下午5点 现在我要做的是确定用户输入的单词在这段时间内是否有效。我有一个很好的例子,但我的问题是周末把一切都搞砸了。我似乎不知道如何让它们工作 我有一个函数来计算两个时间戳之间有多少个周末Php 计算每个阵列的开始和结束日期?,php,Php,我有一个单词数组,从那天下午5点到第二天下午5点,每个单词都是有效的,然后下一个单词就是有效的周末除外在周末,星期五的一个词持续到星期一下午5点 现在我要做的是确定用户输入的单词在这段时间内是否有效。我有一个很好的例子,但我的问题是周末把一切都搞砸了。我似乎不知道如何让它们工作 我有一个函数来计算两个时间戳之间有多少个周末 // Figure out how many weekends occured between two dates function weekends($date1, $da
// Figure out how many weekends occured between two dates
function weekends($date1, $date2) {
$d1 = new DateTime('@' . $date1);
$d2 = new DateTime('@' . $date2);
// Compare the two dates
$diff = $d1->diff($d2);
// Get number of days between them
$days = $diff->format('%a');
// Find out day of the week we start on
$start = $d1->format('w');
// Verify we are not on a weekend
if($start == 0 || $start == 6)
return false;
// Number of days until weekend
$until_weekend = 7 - $start; // (6 is Saturday but we are counting today)
// Find out how many days are left between the first weekend and the end
$left = $days - $until_weekend;
// How many weekends
$weekends = floor($left / 7) + 1;
return $weekends;
}
然后我得到了一个函数来确定这个词在那个日期范围内是否有效
// Keyword Validation
function keyword_validate($keywords = array()) {
if(empty($keywords)) return false;
// Break into values
$keyword = $keywords['keyword'];
$contest = $keywords['contest'];
$keywords = $contest['keywords'];
// Get some dates
$now = new DateTime('now');
$start = new DateTime('@' . $contest['start_time']);
$s1 = new DateTime('@' . $contest['start_time']); // value for timestamps
$s2 = new DateTime('@' . $contest['end_time']); // value for timestamps
$end = new DateTime('@' . $contest['end_time']);
// Verify keyword exists
if(in_array($keyword, $keywords) === FALSE)
return false;
// Get index
$index = array_search($keyword, $keywords);
// See if we somehow got more then one keyword
if(count($index) != 1)
return false;
// get number of weekends
$weekends = weekends($start->getTimestamp(), $end->getTimestamp());
// Based on index get the two container timestamps
$s = $s1->add(new DateInterval('P' . $index + $weekends . 'D'));
// Verify start doesn't equal Friday or a Weekend
$e = $s2->add(new DateInterval('P' . $index + $weekends + 1 . 'D'));
if($s === FALSE || $e === FALSE)
return false; // Something really bad happened
// Based on dates find out if the keyword works.
print $s->getTimestamp();
print $e->getTimestamp();
// Get the current time
}
正如您所看到的,关键字函数不起作用。我现在做的是每天匹配关键字的索引,但是如果是星期二(两个周末之后),我怎么能使索引增加4。对不起,如果这没有任何意义,我有点迷路了。你能不能不要一个可以包含七个空格的数组?当“星期五”索引更改时,将“星期六”/“星期日”设置为镜像。尝试重新定义问题以使其更简单。与其尝试用有趣的异常来计算哪一项与哪一天相关,不如尝试创建一个新数组,每个数组的值为单词。它可能是这样的:
array(
'cake',
'pie',
'pudding',
'happy', //friday
'happy', //saturday
'happy', //sunday
'nothappy',
...
);
构建此阵列应该比您现在要做的事情更简单。一旦你有了这个数组,检查应该是很简单的