如何在 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。

有什么方法可以吗:

  1. 在迭代之间保持 $seat 变量
  2. 重构集合以仅返回足以满足我的 $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;
    });
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...