如何使用我的filter()为Laravel Collections传递变量

时间:2016-02-03 21:10:12

标签: php laravel-5

我有一个我想要过滤的简单集合。请看以下示例:

// 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);

很好,假设我只想过滤'香蕉'。如果我想在过滤器中使用变量,该怎么办?我该怎么做?

// 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);

上述操作无效,因为$filterby功能无法使用filter()。我将如何提供它?

1 个答案:

答案 0 :(得分:1)

你可以“使用”这个变量TH1981,就像这样

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

还有一个提示,您可以使用此全局方法进行收集

$collection = collect($array);