我目前正在使用 only
从 Collection
中提取特定 key 集的方法.此方法从 Collection
中提取指定的键如果 key 不存在,则不提取 key 。我想知道是否还有一种方法可以从 Collection
中提取不存在的 key 并为结果中不存在的键设置默认值。
这是 only
的当前行为方法:
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name', 'quantity']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
我正在寻找的行为是:
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name', 'quantity']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk', 'quantity'=>'']
有没有办法做到这一点?最好使用
Collection
之一的方法。
最佳答案
这可以像这样完成。
// The main collection to filter from
$main = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
// From the filters array, create an empty collection with the default values
$toFilter = collect([
'product_id' => '',
'name' => '',
'quantity' => '',
]);
// Set the the values from the main collection,
$filteredResult = $toFilter->map(function($item, $key) use($main){
return $main[$key] ?? $item ;
});
您应该按预期获得最终集合
$filteredResult->all()
[
"product_id" => 1,
"name" => "Desk",
"quantity" => "",
]
关于php - Laravel 集合 : extract specified set of keys and set the non-existing keys to a default value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61796603/