简体   繁体   中英

Laravel collection rename nested key

How can i rename the key "manufacturer" to, lets say, "test123".

Requirement:

  • Not converting the collection to an array.
  • Not using DB Query "manufacturer as test123".

collection $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: []
}

When i use the following code, i change the value of the properties but not the keys.

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

You can use maps to do the task of manipulating the collection. I have used macro method to define my own method for collection.

Collections are "macroable", which allows you to add additional methods to the Collection class at run time. The Illuminate\Support\Collection class' macro method accepts a closure that will be executed when your macro is called.
--- 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);

It is obvious that this will work only for #items: Illuminate\Support\Collection {#541 ▼ having Illuminate\Support\Collection instance

Ok i found a way without transform. I thought there would be a way to just rename a key. But copy and unset is acceptable, i guess.. Thanks a lot anyway: :)

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

          }
        }
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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