Reputation: 1606
Is there a way to flatten this array:
Array (
[0] => Array (
[country_code] => IM
[language_code] => GB
)
[1] => Array (
[country_code] => GG
[language_code] => JE
)
[2] => Array (
[country_code] => US
[language_code] => US
)
)
to this:
array (
"IM" => "GB"
"GG" => "JE"
"US" => "US"
)
I need to have the first item from each to be the key, and the second item the value.
Update
Is it possible to have multiple values using the secon concept. If I had this array:
Array ( [0] => Array ( [country_code_two] => GBR [country_code_three] => GB [language_code] => EN ) )
and wanted to create the following:
array (
[GBR] => array ([0] => "GB", [1] => "EN")
)
How would this be possible? I am currently using your second option as I dont have 5.5
Upvotes: 1
Views: 65
Reputation: 324610
If you are using PHP 5.5, you can do this: (Docs)
$result = array_column($source, "language_code", "country_code");
If you aren't using PHP 5.5, then you should be :p
More seriously, a backwards-compatible version:
$keys = array_map(function($a) {return $a['country_code'];},$source);
$vals = array_map(function($a) {return $a['language_code'];},$source);
$result = array_combine($keys,$vals);
And if you're somehow stuck on a really old vesion of PHP, the "traditional":
$result = array();
foreach($source as $a) {
$result[$a['country_code']] = $a['language_code'];
}
Upvotes: 3