download1214 2016-01-17 23:09
浏览 71
已采纳

构建一个Carbon对象数组 - PHP

I'm confused trying to add an create an array of date instances with carbon. What I'm trying to achieve is an array with one carbon object for each day in between 2 dates.

Here's what I have so far:

// 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;

So the var_dump from within the loop echo's this:

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" 
         } 
      }

As you can see the second time I output the array the key of 0 has been overwritten by the newer date of 2016-01-18. Anyone have any ideas why?

I'm running php 7.0.0 on mamp with Larvel 5.2.

  • 写回答

1条回答 默认 最新

  • duanlipeng4136 2016-01-18 10:28
    关注

    In PHP, except where otherwise noted, objects are assigned by reference rather than by value. That means that every time you assign an object to a variable you just store a reference to the same object. That's shown in your var_dump() code, all objects are the same #238:

    object(Carbon\Carbon)#238
    

    The general solution is to either use an immutable object (if available) or just clone the existing one:

    while ($diff >= 0) {
        $filters[$i] = clone $carbonFrom->addDays($i);
        $diff--;
        $i++;
        var_dump($filters);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题