我从数据库中检索了这个数组:
Array $result['cities']
(
[1] => New York, United States
[2] => London, United Kingdom
)
这个关联数组:
Array $asso
(
[United States] => us
[United Kingdom] => gb
)
现在,我想将第一个数组转换为:
Array $newArray
(
[1] => us
[2] => gb
)
当然,它必须是动态的。我尝试使用这个但是一旦if条件成立,我就不知道如何选择匹配的密钥:
if (in_array('New York, United States', $result['cities'])) {
/// So select the matched value and replace it with "us"...
}
if (in_array('London, United Kingdom', $result['cities'])) {
/// So select the matched value and replace it with "gb"...
}
因此,正如您所理解的,我的问题可以翻译为:如何将数组A值替换为数组B的值,其中A值是B键?
答案 0 :(得分:3)
试试这个 -
foreach($result['cities'] as $key => $cityInfo){
list($city, $country) = explode(',', $cityInfo);
if(isset($asso[$country])){
$newArr[$key] = $asso[$country];
}
}
答案 1 :(得分:0)
$newArray = array_map(function ($e) use ($asso) {
$countryName = trim(array_pop(explode(',', $e)));
return $asso[$countryName];
}, $result['cities']);