如何在 Laravel 集合中的迭代之间保留一个值?

How to persist a value between iterations in a Laravel Collection?

在我的应用程序中,Table 可以容纳一定数量的食客。我需要编写一个集合,其中 return 仅包含我需要容纳给定数量的食客的桌子数量。

例如,如果我要容纳四个用餐者,而只有 table 个可以容纳一个,我 return 四个 table 个。如果我有一个 table 可容纳四个或更多的人,我只 return table.

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。

有什么方法可以:

  1. 在迭代之间保留 $seat 变量
  2. 将集合重构为 return 只够满足我的 $numberOfGuests
  3. 的表

您要做的是通过 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;
    });
}