简体   繁体   中英

How do I pass through a variable with my filter() for Laravel Collections

I have a simple collection that I want to filter. Take the following example:

// Create an array of fruits
$array = ["banana", "apple", "orange"];

// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);

// We don't like banana's anymore, so we're going to filter them out
$no_bananas = $collection->filter(function($element) {
    if ($element != "banana") return true;
});

// Dump out our array now, and we'll see the banana's are gone
dd($no_bananas);

Works great assuming I only ever want to filter by 'banana'. What if I want to use a variable within the filter. How do I do that?

// Create an array of fruits
$array = ["banana", "apple", "orange"];
$filterby = 'apple';

// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);

// We don't like banana's anymore, so we're going to filter them out
$filtered = $collection->filter(function($element) {
    if ($element != $filterby) return true;
});

// Dump out our array now, and we'll see the banana's are gone
dd($filtered);

The above won't work because $filterby isn't available in the filter() function. How would I make it available?

You can 'use' this variable TH1981, like this

$filtered = $collection->filter(function($element) use ($filterby) {
    return $element != $filterby;
});

and one more tip you can make a collect with this global method

$collection = collect($array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM