簡體   English   中英

如何在 Laravel 集合中的迭代之間保留值?

[英]How to persist a value between iterations in a Laravel Collection?

在我的應用程序中,一張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. 重構集合只返回足夠的表來滿足我的$numberOfGuests

您想要做的是通過引用傳遞您的$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;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM