How to add value into an array inside of each meth

2019-08-07 12:51发布

问题:

I use Laravel5.4.

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.

please help me!

# Pattern A

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

        }

}

Pattern 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) { }

        }

}

How come?

And how should I fix it?

回答1:

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**);
}


回答2:

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.";

            $bounceZoneList[] = 1;

        });

        var_dump($bounceZoneList); // array(0) { }

        }

}

NG - use (bounceZoneList)

OK - use (&bounceZoneList)