如何解决如何在 Laravel 集合中的迭代之间保留值?
在我的应用中,Table
可以容纳一定数量的用餐者。我需要编写一个集合,该集合只返回我需要容纳给定数量的用餐者的桌子数量。
例如,如果我必须容纳四个用餐者,而只有一张桌子,我会返回四张桌子。如果我有一张可容纳 4 人或更多人的桌子,我只会退回那张桌子。
public function filterTablesWithSeating($numberOfGuests)
{
$seats = 0;
return Table::get()->map(function ($table) use ($seats,$numberOfGuests) {
if ($seats >= $numberOfGuests) {
return false; // Break the collection
}
$seats = $seats + $table->can_seat;
return $table;
});
}
这理论上完成了我想要做的事情,只是因为 $seats
是在集合之外定义的,所以我无法直接更新它。随着集合的每次迭代,它被重新定义为 0。
有什么方法可以吗:
- 在迭代之间保持
$seat
变量 - 重构集合以仅返回足以满足我的
$numberOfGuests
的表
解决方法
您想要做的是通过 reference 传递您的 $seats
,这将允许您的循环更新它。
public function filterTablesWithSeating($numberOfGuests)
{
$seats = 0;
// Add the ampersand before your $seats to pass by reference
return Table::get()->map(function ($table) use (&$seats,$numberOfGuests) {
if ($seats >= $numberOfGuests) {
return false; // Break the collection
}
$seats = $seats + $table->can_seat;
return $table;
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。