1

我正在制作一个函数,我试图以不同的日期格式存储数据。我想根据有多少天将数据存储在几个月或几周内。所以基本上,我的意思是说,如果我从两个月内获取数据,我希望它每周将数据存储在一个数组中,例如:

'1 2013' => 'some data',
'2 2013' => 'some data',
'3 2012' => 'some data',

如果我要获取超过三个月的数据,我想每月存储数据,所以:

'Jan 2013' => 'some data',
'Feb 2013' => 'some data',
'Mar 2012' => 'some data',

想考虑到我可能想要添加更多场景,所以我做了一个条件来根据天数确定数据的存储方式。它适用于几个月,但由于某种原因它不适用于几周。我不断在循环中为日期添加一周以获取下一个日期。当我在调用 strtotime() 后检查 $time 变量的类型时,它说它是布尔类型。不明白为什么!

这是我的代码的相关部分(为清楚起见,编辑了位):

$times = array();
$length = 90;                   //Fetched data for 90 days.
$periods= round($length/7);     //Want to divide it up into weeks.
$per = 'week';
$format= 'W Y';

for($n = 0; $n < $periods; $n++){
    $time               = date($format, $start);

       //Here's apparently where it goes wrong:

    $time               = date($format, strtotime($time . ' + ' . $n . $per));
    $times[$time] = array();
}

e:想添加,即使我这样做:

$time = date($format, strtotime($time . ' + 1 week'));

它不会存储正确的值。

4

4 回答 4

2

我希望这个例子可以帮助你;当我处理日期时,我喜欢 DateTime 对象,请看下面的代码(我希望评论能解释清楚)

$times = array(); //array to hold values in

$Start = new DateTime('01-01-2013'); //the start date, may come from db??

$End = new DateTime('01-02-2013'); //the end date (You can also create a new DateTime object and add 90 days if you want)


$Diff = $Start->diff($End); //check how many days are between the two dates, if higher than 90, format by month, else by week

if ($Diff->days > 90) { //from 90 days, show per month instead of weeks
    $per = 'month';
    $format = 'm Y';
} else {
    $per = 'week';
    $format = 'W Y';
}

while($Start < $End) { //loop until $Start equals or is higher than $End

    $times[$Start->format($format)] = 'some data'; //push data into the array 

    $Start->modify('+1 ' . $per); //add X amount of time to the $Start variable 
}


print_r($times);

这段代码显示:

Array
(
    [01 2013] => some data
    [02 2013] => some data
    [03 2013] => some data
    [04 2013] => some data
    [05 2013] => some data
)
于 2013-07-24T13:49:49.917 回答
1

在此处更改逻辑并迭代结果项并将它们直接“放入”正确的定期分组可能是个好主意(未经测试,但我相信您会明白的):

$times = Array();

// apply format for groupings
$format= 'W Y'; 

// traverse results item by item
foreach($results as $item){

    // assumed content of result here - this has to be adapted
    $timestamp = $item['timestamp'];
    $value = $item['value'];
    $key = date($format, $timestamp);

    // new grouping so create new key
    if(!isset($times[$key])) $times[$key] = Array();

    // add item
    $times[$key][] = $value;
}
于 2013-07-24T13:54:58.073 回答
0

strtotime 接受的格式是字符串,因此您需要在添加日期之前将 $time 转换为字符串。

所以,

 $time               = date($format, strtotime($time->format('Y-m-d')->toString() . ' + ' . $n .' '. 'weeks')); //i think it might be plural "weeks" no "week"
于 2013-07-24T13:45:32.590 回答
-1

阅读此功能: PHP 手册:DateTime:add

于 2013-07-24T13:42:00.343 回答