【问题标题】:Laravel collection rename nested keyLaravel 集合重命名嵌套键
【发布时间】:2021-04-18 05:15:59
【问题描述】:

如何将键“制造商”重命名为“test123”。

要求:

  • 不将集合转换为数组。
  • 不使用数据库查询“manufacturer as test123”。

收藏$stuff:

Illuminate\Pagination\LengthAwarePaginator {#543 ▼
  #total: 14
  #lastPage: 3
  #items: Illuminate\Support\Collection {#541 ▼
    #items: array:5 [▼
      0 => {#447 ▼
        +"id": 30
        +"title": "some nice title"
        +"properties": array:4 [▼
          "price" => "99999"
          "manufacturer" => "Puma"
          "model" => "some model"
          "condition" => "new"
        ]
      }
      1 => {#449 ▶}
      2 => {#448 ▶}
      3 => {#450 ▶}
      4 => {#445 ▶}
    ]
  }
  #perPage: 5
  #currentPage: 1
  #path: "https://some-nice-url.com"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: []
}

当我使用下面的代码时,我改变了属性的值而不是键。

   foreach ($stuff as $key => $value) {
      if(!empty($value->properties)) {
        foreach ($value->properties as $key2 => $value2) {
          if(array_key_exists($key2, $ok))
          {
            $value->properties[$key2] = $ok[$key2]['name'];
          }
        }
      }
    }

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以使用地图来完成操作集合的任务。我已经使用宏方法定义了自己的收集方法。

    集合是“可宏化的”,它允许您在运行时向 Collection 类添加其他方法。 Illuminate\Support\Collection 类的宏方法接受将在调用宏时执行的闭包。
       --- Extending-collections


    Collection::macro('toChangeManufacturerKeyToTest123', function () {
                return $this->map(function ($value, $key) {
                    $value["properties"]["test123"] = $value["properties"]["manufacturer"];
                    unset($value["properties"]["manufacturer"]);
                    return $value;
                });
            });
    
    $updatedStuff = $stuff->toChangeManufacturerKeyToTest123();
    dd($updatedStuff);
    

    很明显,这仅适用于具有Illuminate\Support\Collection 实例的#items: Illuminate\Support\Collection {#541 ▼

    【讨论】:

    • 感谢您的回复。它在 "$value["properties"]["test123"] = $value["properties"]["manufacturer"];" 行上给了我“错误不能使用 stdClass 类型的对象作为数组”仅更改键名似乎更加复杂。我知道 collection->transform 可能会起作用,但我不知道如何。
    • 你能在 map 函数中显示什么是 dd($value),因为答案适用于集合实例,但你的集合实例在 LengthAwarePaginator 实例内部更远
    【解决方案2】:

    好的,我找到了一种无需转换的方法。我认为有一种方法可以重命名一个键。但是复制和取消设置是可以接受的,我猜.. 非常感谢! :)

        foreach ($stuff as $key => $value) {
    
          if(!empty($value->properties)) {
    
            foreach ($value->properties as $key2 => $value2) {
    
              if(array_key_exists($key2, $ok))
              {
    
                $value->properties[$ok[$key2]['name']] = $value2;
                unset($value->properties[$key2]);
    
              }
            }
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2021-04-09
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多