在 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"
          ]
        ]
      }
    }
  ]
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...