问题描述
在我的应用中,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;
});
}