How to get the key based on values? Hey,
say that I have this:
$array = [
'english' => [
'USA',
'Canada',
'Australia'
],
'spanish': [
'Spain',
'Venezuela'
]
];
How can I simply, using collect() or Arr::, get english from USA?
Thanks
collect($array)->mapWithKeys(
fn ($item, $key) => collect($item)->mapWithKeys(
fn ($element) => [$element => $key]
)
)->get('USA')
This could probably be improved, but works so long as a country is not listed under more than one language ¯\_(ツ)_/¯
Thanks for that, it's an interesting approach.
Could there be another way of going about it from the beginning? Maybe my array is wrong. The point is that I want to have a "top value" (english) for multiple "lower values" (countries). But the array will grow overtime, so I can set it in stone.
As @tykus pointed out you have it nested so you have to "double" the method to get to the nested level.
@romain
$array = [
'english' => [
'USA',
'Canada',
'Australia'
],
'spanish'=> [
'Spain',
'Venezuela'
]
];
return collect($array)->filter(function($value, $key){
if(in_array('USA', $value)){
return true;
}
return false;
})->keys();
It may not be the best but it works. Use Collection filter
Thanks for your reply, you have the same as @corvs but his is a one liner and that would be my preference, so I will make his the best answer.
@romain Is it possible that a country exists for multiple keys?
$langKey = collect($array)->filter(fn($lang) => in_array('USA', $lang))->keys()->first();
@romain Then you can add ->first() at the end to get only the single key.
Yep I'll do that. Just tested and it works as expected. I'll set your first reply as the best answer, please add ->first() in it.
Thanks again
Please sign in or create an account to participate in this conversation.