Laravel Collection Push()无法正常工作



我试图根据日期范围重复集合中的项目。例如,我有一个:

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

现在我想复制6倍,因为有6天的12-20至12-25。这样:

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

我想要这个,因为我以前的问题的答案是:在日期开始和结束

上重复事件。

这是我的代码:

$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();

,但我唯一获得的输出是它根据最后一个日期" 2017-12-25"重复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
}

问题是:

$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/support/collection.php#l1129

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

相关内容

  • 没有找到相关文章