如何在Collection对象的每个方法内部的数组中添加值

如何在Collection对象的每个方法内部的数组中添加值

问题描述:

我使用Laravel5.4.

I use Laravel5.4.

我想将值添加到Collection对象的每个方法内部的数组中.

I want to add values to an array inside of each method of Collection object.

这应该很简单,但不起作用.

This should be easy and simple but it doesn't work.

下面的代码是我的工作代码的简化版本.

The code below is the simplified version of my working code.

请帮助我!

class ReportController extends Controller
{


    public function daily(ReportRequest $request) {

        $collection = VisitRecord::whereDate('visited_at', '=', Carbon::today())->get();

        $bounceZoneList = [];

        $collection->groupBy("bounce_zone")->each(function($group, $key) {

            echo "this line is called.";

            //add value to the array!
            $bounceZoneList[] = 1;

        });

        //but it doesn't have any value!
        var_dump($bounceZoneList); // array(0) { }

        }

}

模式B

class ReportController extends Controller
{


    public function daily(ReportRequest $request) {

        $collection = VisitRecord::whereDate('visited_at', '=', Carbon::today())->get();

        $bounceZoneList = [];

        $collection->groupBy("bounce_zone")->each(function($group, $key) use ($bounceZoneList) {

             echo "this line is called.";

            //add value to the array!
            $bounceZoneList[] = 1;

        });

        //but it doesn't have any value!
        var_dump($bounceZoneList); // array(0) { }

        }

}

怎么来?

该如何解决?

在您的* each *闭包中,首先返回键,因此它是function($key,$group)
$group作为集合返回,因此您可以循环使用它
尝试:

Within your *each* closure, the keys are returned first, so it's function($key,$group)
The $group is returned as a collection, so you can cycle through it with a loop
Try :

$group->each(function($item){
      array_push($bounceZoneList,$item->**the_entry_you_want_to_be_pushed_to_the_array**);
}