繁体   English   中英

Laravel 集合重命名嵌套键

[英]Laravel collection rename nested key

我如何将密钥“制造商”重命名为“test123”。

要求:

  • 不将集合转换为数组。
  • 不使用数据库查询“制造商作为 test123”。

收集$东西:

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'];
          }
        }
      }
    }

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

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


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);

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

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

    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]);

          }
        }
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM