【问题标题】:Building an array of Carbon Objects - PHP构建碳对象数组 - PHP
【发布时间】: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


    【解决方案1】:

    在 PHP,except where otherwise noted 中,对象是通过引用而不是值来分配的。这意味着每次将对象分配给变量时,您只需存储对相同对象的引用。这在您的var_dump() 代码中显示,所有对象都是相同的#238:

    object(Carbon\Carbon)#238
    

    一般的解决方案是使用不可变对象 (if available) 或直接克隆现有对象:

    while ($diff >= 0) {
        $filters[$i] = clone $carbonFrom->addDays($i);
        $diff--;
        $i++;
        var_dump($filters);
    }
    

    【讨论】:

    • 正确。就像在 C 或 C++ 中一样,因此您使用“->”而不是“.”来访问函数和属性,它是对对象的引用。
    【解决方案2】:

    这是实现与 2022 年 2 月相同功能的更合适的方法(使用 Carbon v2.57):

    $dates = CarbonPeriod::create($startDate, $endDate)->toArray();
    

    干杯!

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 2021-02-06
      • 2018-03-02
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2020-06-08
      • 1970-01-01
      相关资源
      最近更新 更多