Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection to associative array with specific keys [L5.2]

I have the next collection:

Collection {#356 ▼
  #items: array:31 [▼
    0 => {#359 ▼
      +"id": 17
      +"zone_id": 2
      +"name_de": "Österreich"
      +"name_en": "Austria"
      +"name_iso": "AUSTRIA"
      +"tld": "at"
      +"iso3166": "AT"
      +"phone": 43
      +"vat_regex": "/^U[0-9]{8}$/"
      +"shop_id": 17
      +"country_id": 165
    }
    1 => {#360 ▼
      +"id": 2
      +"zone_id": 2
      +"name_de": "Belgien"
      +"name_en": "Belgium"
      +"name_iso": "BELGIUM"
      +"tld": "be"
      +"iso3166": "BE"
      +"phone": 32
      +"vat_regex": "/^[01][0-9]{9}$/"
      +"shop_id": 17
      +"country_id": 25
    }]
}

And I want to get the next result as associative array:

[
    "AT" => "Austria",
    "BE" => "Belgium"
]

I'm trying to do it using:

$keyed = $countries->map(function ($item) {
     return [$item->iso3166 => $item->name_en];
});

But I'm getting:

Collection {#357 ▼
  #items: array:31 [▼
    0 => array:1 [▼
      "AT" => "Austria"
    ]
    1 => array:1 [▼
      "BE" => "Belgium"
    ]
  ]
}

What I'm doing wrong or how can I achieve the associative array?

Note: I'm using Laravel 5.2 so mapWithKeys() Collection method is not implemented.

like image 519
Troyer Avatar asked May 29 '17 08:05

Troyer


People also ask

Which key is used in associative array?

Traversing the Associative Array Example: In Associative arrays in PHP, the array keys() function is used to find indices with names provided to them, and the count() function is used to count the number of indices.

How can you access the elements of an associative array?

The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP. Although the array_keys() function can be used to get an indexed array of keys for an associative array.

What is associative array with example?

Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.

How do you print the key in an associative array?

Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.


1 Answers

You want to use function ->pluck('name_en', 'iso3166').

like image 99
Kyslik Avatar answered Sep 21 '22 22:09

Kyslik