【问题标题】:How to store data to an array inside foreach loop in Laravel?如何将数据存储到 Laravel 的 foreach 循环内的数组中?
【发布时间】:2020-10-03 06:10:57
【问题描述】:

我有一个 $linesheetItems 的集合,现在我需要在 foreach 循环 中循环这些 $linesheetItems 并使用 line sheet 项目的季节代码存储一个季节数组 ($linesheetItem['season'])。但是根据我目前的代码,它返回一个空数组。

代码:

$seasons = [];
foreach($linesheetItems as $linesheetItem) {
    $seasons = Season::where('code', $linesheetItem['season'])->get();
}

dd($seasons);

如何实现这一点,我应该对我的代码做哪些修改?

【问题讨论】:

    标签: arrays laravel eloquent


    【解决方案1】:

    在您的代码中,每次循环运行时,您都会覆盖$seasons 变量。为了将项目添加到数组中,您必须设置 $seasons[] = Season::where('code', $linesheetItem['season'])->get();。这将始终将新项目推送到数组中。如果你想在数组上有自定义键,你可以做$seasons['your-key'] = Season::where('code', $linesheetItem['season'])->get();

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多