0

(现在已修复且工作正常,但如果有人仍想重构,请留言)

这是我拥有的一个函数的精简版本,它迭代一个日期范围并为每个函数分配一个唯一的整数......

在处理大型数据集时,在不同的日期范围内多次运行,我遇到了一个致命错误,为脚本分配了太多内存,它在这个循环中死了......

Fatal error: Allowed memory size of 268435456 bytes exhausted

已修复,是迭代未考虑潜在夏令时的问题

所以,我想知道是否有人可以推荐一种更优化的方法来生成这个月/整数列表......

它必须允许我以我喜欢的任何数字开始 Int 并且

<?php
// updated: 2010.11.04 with Qwerty's recommendations 
//  for fixing daylight savings time issue
function monthIterate($monthInt, $startDate, $stopDate) {
    $epoch = $startMain = strtotime($startDate);
    $stopMain = strtotime($stopDate);
    while ($epoch <= $stopMain) {
        // get the start/stop dates for "this month"
        $start = date("Y-m-01", $epoch);
        $stop = date("Y-m-t", $epoch);
        // uniqueID for the month
        $monthKey = "Month#-".str_pad($monthInt, 3, "0", STR_PAD_LEFT);
        $months[$monthKey] = compact('start', 'stop');
        // move forward in loop, +1 day should get us to the next month
        $epoch = strtotime($stop);
        $currentMonth = $nextMonth = date('m', $epoch);
        while ($currentMonth == $nextMonth) {
            $epoch = $epoch + 86400;
            $nextMonth = date('m', $epoch);
        }
        $monthInt++;
    }
    return $months; 
}
?>
4

2 回答 2

2

由于节省了额外的一小时光节约时间,您的函数似乎陷入了无限循环。

echo date('Y-m-d H:i:s', strtotime('2010-10-31') + 60*60*2); // adding 2 hours
echo date('Y-m-d H:i:s', strtotime('2010-10-31') + 60*60*3); // adding 3 hours

两者都会输出2010-10-31 02:00:00strtotime('2010-10-31') + 86400实际上是这样2010-10-31 23:00:00,但不是第二天。

所以你应该增加超过 86400 秒以确保你切换到第二天:-)

于 2010-11-04T20:51:55.107 回答
0

我认为您的数组索引太疯狂了。

IE :

[Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-Month#-123] => Array
(
    [start] => 2011-12-01
    [stop] => 2011-12-31
)

我会移动你的 "$monthInt = "Month#-".str_pad($monthInt, 3, "0", STR_PAD_LEFT);" 循环外的行。

<?php
function monthIterate($monthInt, $startDate, $stopDate) {

$monthInt = "Month#-".str_pad($monthInt, 3, "0", STR_PAD_LEFT); <--

$epoch = $startMain = strtotime($startDate);
$stopMain = strtotime($stopDate);
while ($epoch <= $stopMain) {
    // get the start/stop dates for "this month"
    $start = date("Y-m-01", $epoch);
    $stop = date("Y-m-t", $epoch);
    // uniqueID for the month
    $months[$monthInt] = compact('start', 'stop');
    // move forward in loop, +1 day should get us to the next month
    $epoch = strtotime($stop) + 86400;
    $monthInt++;
}
return $months; 
}?>
于 2010-11-04T21:10:20.773 回答