本文介绍了如何在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**);
}
这篇关于如何在Collection对象的每个方法内部的数组中添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!