我使用的是Laravel5.4。
我想在Collection对象的每个方法内的数组中添加值。
这应该简单易行,但不起作用。
以下代码是我工作代码的简化版本。
请帮助我!
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) { }
}
}
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) { }
}
}
怎么回事?
我该如何解决?
答案 0 :(得分:1)
在* each *闭包中,首先返回键,因此subClientKoEligible
function($key,$group)
作为集合返回,因此您可以循环遍历它
试试:
$group
答案 1 :(得分:0)
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 - 使用(bounceZoneList)
确定 - 使用(& bounceZoneList)