php - Laravel 集合 : extract specified set of keys and set the non-existing keys to a default value

标签 php laravel eloquent

我目前正在使用 onlyCollection 中提取特定 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/

相关文章:

javascript - 单击复选框然后使用 jquery 删除验证

php - 将其他计算输入 DATEDIFF

php - 使用 onesignal 向特定用户发送通知

php - 渴望加载在一对多关系上返回 null

php - Laravel - 四层深度关系

php - MySQL:子查询是正确的做法吗?

php - 本地主机上的 Symfony3 和 gmail

php - 如何使 laravel 多对一(hasMany)关系有效

php - 有没有一种简单的方法可以仅在 View Laravel 上更改时区?

laravel - Eloquent ORM - 检索与给定模型无关的模型(多对多关系)