我正在创建一个函数,我正在尝试以不同的日期格式存储数据。我想在几个月或几周内存储数据,具体取决于有多少天。基本上,我的意思是说,如果我从两个月获取数据,我希望它每周将数据存储在一个数组中,如:
'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'));
它不会存储正确的值。
答案 0 :(得分: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
)
答案 1 :(得分: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;
}
答案 2 :(得分:0)
strtotime接受的格式是字符串,因此您需要在添加日期之前将$ time转换为字符串。
所以,
$time = date($format, strtotime($time->format('Y-m-d')->toString() . ' + ' . $n .' '. 'weeks')); //i think it might be plural "weeks" no "week"
答案 3 :(得分:-1)
阅读此功能: PHP Manual: DateTime:add