通过许多组合迭代时,请避免深嵌套



是否有更多声明/较少恐怖的写作方式(故意简化(代码?

我意识到我可以使用->each(),但是在这种情况下,这仍然不会摆脱嵌套?

注意i 确实需要才能生成 all 组合,我有很多可以循环循环的事物 - 配置数据,普通数组,雄辩,尽管显然我可以首先转换它们...

    foreach(config('app.goals') as $goal) {
      foreach(config('app.age_groups') as $ages) {
        foreach($regions as $region_name => $region_id) {
          foreach($interests->pluck('name')->prepend('') as $interest) {
            foreach(config('app.devices') as $device) {
              $record = new Foo();
              $record->goal = $goal;
              $record->age  = $age;
              $record->region = $region_id;
              $record->interest = $interest;
              $record->device = $device;
              $record->save();
            }
          }
        }
      }
    }

不清楚是否有收集方法可以提供帮助?例如

holygrail(config('app.goals'),config('app.age_groups'),$regions...)->each(function($combination) {
    // logic for every combination
});

crossjoin((似乎做了我需要的事情,它创建了每个组合的数组矩阵。

$matrix = collect($goals)->crossJoin(
            $ages,
            $regions,
            $interests,
            $devices
);

因此,您有一个充满元素的数组,每个元素都是置换的,例如:

array(5) {
  [0]=>
  string(5) "REACH"
  [1]=>
  string(5) "18-65"
  [2]=>
  string(9) "Worldwide"
  [3]=>
  string(11) "Programming"
  [4]=>
  string(7) "desktop"
}

laravel源在: Illuminate support arr :: crossjoin

最新更新