【问题标题】:Laravel 从 $collection->each() 循环内部访问变量 [重复]
【发布时间】:2022-01-21 12:15:06
【问题描述】:

我想使用 each() 循环从现有集合构建一个新集合:

$spot = Spot::where('slug', $slug)->first()->load('features.group');

$test = collect();

$spot->features->each(function ($item, $key) {
    $current = collect([
        $item->group->name => $item->name,
    ]);
    $test->mergeRecursive($current);
});
    
dd($test);

我从循环内的代码中收到错误 Undefined variable $test。如何从循环内部访问$test 集合?

谢谢!

【问题讨论】:

    标签: php eloquent laravel-8


    【解决方案1】:

    您可以通过use() 在闭包内传递数据。试试这个:

    $spot = Spot::where('slug', $slug)->first()->load('features.group');
    
    $test = collect();
    
    $spot->features->each(function ($item, $key) use(&$test) {
        $current = collect([
            $item->group->name => $item->name,
        ]);
        $test->mergeRecursive($current);
    });
        
    dd($test);
    

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 2010-11-22
      相关资源
      最近更新 更多