A
A
Anton October2018-02-15 16:12:38
Laravel
Anton October, 2018-02-15 16:12:38

How to set the value of keys in Laravel collections?

Here is a code snippet:

dd(FuwMapping::where('template','=','NB5215')->get()->map(function($item) use ($content) {
            $value = array_get($content, $item->json_field);
            return $value;
        }));

As a result I have:
Collection {#233
  #items: array:7 [
    0 => "Broker Dealer"
    1 => "F. M.  Dostoevsky"
    2 => "999-99-9999"
    3 => "(999) 999-9999"
    4 => "[email protected]"
    5 => null
    6 => "01/01/1980"
  ]
}

How to replace keys 0,1,2,3... with custom values ​​in this example it is $item->pdf_field

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton October, 2018-02-15
@Lyrium

The solution was the mapWithKeys() method

dd(FuwMapping::where('template','=','NB5215')->get()->mapWithKeys(function($item) use ($content) {
            return [$item->pdf_field => array_get($content, $item->json_field)];
        }));

method-mapwithkeys
result:
Collection {#412
  #items: array:7 [
    "Firm" => "Broker Dealer"
    "ProducerName" => "F. M.  Dostoevsky"
    "SSN" => "999-99-9999"
    "PhoneNumber" => "(999) 999-9999"
    "Email" => "[email protected]"
    "InsuredName" => null
    "InsuredBirth" => "01/01/1980"
  ]
}

A
Alexey Ukolov, 2018-02-15
@alexey-m-ukolov

https://laravel.com/docs/5.6/collections#method-keyby
In general, you are doing some nonsense, judging by the data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question