如何解决在 Laravel 中转换嵌套集合
我有一个想要转换的嵌套集合,将一些键“上一层”并丢弃一些其他键。
集合中的每个项目都有过敏原属性。
"allergens": [
{
"id": 2001,"info": "Allergy advice","status": "does_contain","product_id": 71576,"allergen_id": 1,"allergen": {
"id": 1,"name": "Celery"
}
},{
"id": 2002,"status": "may_contain","allergen_id": 11,"allergen": {
"id": 11,"name": "Peanuts"
}
}
],
我需要让每件物品都具有过敏原属性,看起来像
"allergens": [
{
"id": 1,"name": "Celery"
"status": "does_contain",},{
"id": 11,"name": "Peanuts"
"status": "does_contain",],
我尝试了以下方法:
$collection = $collection->transform(function ($item,$key) {
$item->allergens = $item->allergens->map(function ($allergen) {
return [
'id' => $allergen->allergen->id,'name' => $allergen->allergen->name,'status' => $allergen->status,];
});
return $item;
});
但它不会覆盖 allergens
属性
解决方法
由于您将集合发布为 JSON,因此我对您的实际集合的外观进行了逆向工程。事实证明,据我所知,您的 transform()
工作正常。也许这可以帮助您找到我的和您的收藏之间的差异,这可能会引导您解决问题/解决方案:
$collection = collect([
(object)[
"allergens" => collect([
(object)[
"id" => 2001,"info" => "Allergy advice","status" => "does_contain","product_id" => 71576,"allergen_id" => 1,"allergen" => (object)[
"id" => 1,"name" => "Celery"
]
],(object)[
"id" => 2002,"status" => "may_contain","allergen_id" => 11,"allergen" => (object)[
"id" => 11,"name" => "Peanuts"
]
]
]),]
]);
$collection = $collection->transform(function ($item,$key) {
$item->allergens = $item->allergens->map(function ($allergen) {
return [
'id' => $allergen->allergen->id,'name' => $allergen->allergen->name,'status' => $allergen->status,];
});
return $item;
});
dd($collection);
结果:
Illuminate\Support\Collection {#1779 ▼
#items: array:1 [▼
0 => {#1791 ▼
+"allergens": Illuminate\Support\Collection {#1775 ▼
#items: array:2 [▼
0 => array:3 [▼
"id" => 1
"name" => "Celery"
"status" => "does_contain"
]
1 => array:3 [▼
"id" => 11
"name" => "Peanuts"
"status" => "may_contain"
]
]
}
}
]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。