【发布时间】:2022-02-27 04:22:58
【问题描述】:
我很困惑尝试使用碳添加创建日期实例数组。我想要实现的是一个数组,在两个日期之间的每一天都有一个碳对象。
这是我目前所拥有的:
// Get oldest and newest date by sorting the array by created_at
usort($data, function($a, $b) {
return $a->created_at <=> $b->created_at;
});
$a = end($data);
$to = $a->created_at; //-> Newest date
$from = $data[0]->created_at; //-> Oldest date
// Work out the difference between to and from dates
$carbonTO = new Carbon($to);
$carbonFrom = new Carbon($from);
$diff = $carbonFrom->diffInDays($carbonTO);
// Write the dates to an array
$i = 0;
while ($diff >= 0) {
$filters[$i] = $carbonFrom->addDays($i);
$diff--;
$i++;
var_dump($filters);
}
die();
return $filters;
所以循环中的 var_dump 是这样的:
array(1) {
[0]=> object(Carbon\Carbon)#238 (3) {
["date"]=> string(26) "2016-01-17 19:04:49.000000"
["timezone_type"]=> int(3)
["timezone"]=> string(3) "UTC"
}
}
array(2) {
[0]=> object(Carbon\Carbon)#238 (3) {
["date"]=> string(26) "2016-01-18 19:04:49.000000"
["timezone_type"]=> int(3)
["timezone"]=> string(3) "UTC"
}
[1]=> object(Carbon\Carbon)#238 (3) {
["date"]=> string(26) "2016-01-18 19:04:49.000000"
["timezone_type"]=> int(3)
["timezone"]=> string(3) "UTC"
}
}
如您所见,我第二次输出数组时,键 0 已被较新的日期 2016-01-18 覆盖。任何人有任何想法为什么?
我正在使用 Larvel 5.2 在 mamp 上运行 php 7.0.0。
【问题讨论】:
标签: php php-carbon