繁体   English   中英

如何将数据存储到 Laravel foreach 循环内的数组中?

[英]How to store data to an array inside foreach loop in Laravel?

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

代码:

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

dd($seasons);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM