Laravel5.4のコレクションオブジェクトのeachメソッド内で外側のスコープの配列に値を代入したいのですが、上手くいきません。
単純な話だと思うのですが、、、なんで、うまくいかないのでしょうか?
※namespaceやuseは以下のコードで省略しております。
パターン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 "ちゃんとループ内は読まれてます"; //試しに追加! $bounceZoneList[] = 1; }); //でも、からっぽのまま! 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 "ちゃんとループ内は読まれてます"; //試しに追加! $bounceZoneList[] = 1; }); //でも、からっぽのまま! var_dump($bounceZoneList); // array(0) { } } }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/05/15 09:39