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.
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.
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.
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.
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.
You want to use function ->pluck('name_en', 'iso3166')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With