Laravel Collection push()没有正常工作

时间:2017-12-21 02:39:54

标签: php json laravel collections fullcalendar

我正在尝试根据日期范围复制集合中的项目。例如,我有一个JSON:

{
"title": " 200",
"start": "2017-12-20",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

现在我要复制6x,因为从12-20到12-25有6天。像这样:

{
"title": " 200",
"start": "2017-12-20",
"endx": "2017-12-20",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-21",
"endx": "2017-12-21",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-22",
"endx": "2017-12-22",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-23",
"endx": "2017-12-23",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-24",
"endx": "2017-12-24",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

我之所以这样,是因为上一个问题的回答:Repeat events on FullCalendar base on date start and end

这是我的代码:

$events = Event::all();

        foreach ($events as $i => $event) {
            if($event->start != $event->endx)
            {
                $date = $event->start;
                $end = $event->endx;
                while (strtotime($date) <= strtotime($end)) {
                    $new = [];
                    $new = $event;

                    $new->start = $date;
                    $new->endx = $date;

                    $events->push($new);

                    $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
                }
            }
        }

        return $events->all();

但我得到的唯一输出是它根据最后日期&#34; 2017-12-25&#34;重复6次。像这样:

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

{
"title": " 200",
"start": "2017-12-25",
"endx": "2017-12-25",
"equipment": "Chairs",
"quantity": 200
}

1 个答案:

答案 0 :(得分:5)

问题是:

$new是一个对象。您推送到该集合的$new与您在下一次迭代中使用的$new相同。进一步描述情况:

$a = new stdClass;
$a->name = "foo";

$myArray = [$a];

var_dump($myArray);
// array(1) {
//  [0]=>
//  object(stdClass)#1 (1) {
//    ["name"]=>
//    string(3) "foo"
//  }
//}

$a->name = "bar";
var_dump($myArray);
// array(1) {
//  [0]=>
//  object(stdClass)#1 (1) {
//    ["name"]=>
//    string(3) "bar"
//  }
//}

$new通过引用push方法传递,或者有些人会说,通过引用分配。

这就是你的情况下发生的魔力,为了解决这个问题,你应该推送一个$new的克隆对象。

您可以在此处跟踪push代码:https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Collection.php#L1129

$events->push($new);更改为$events->push(clone $new);