cyclone200 cyclone200 - 6 months ago 9
PHP Question

Replace value with two arrays

I have this array retrieved from database :

Array $result['cities']
(
[1] => New York, United States
[2] => London, United Kingdom
)


And this associative array :

Array $asso
(
[United States] => us
[United Kingdom] => gb
)


Now, I would like to transform the first array into this:

Array $newArray
(
[1] => us
[2] => gb
)


Of course, it has to be dynamic. I tried by using this but once the if condition is true, I don't know how to select the matched key :

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"...
}


So, as you understand, my problem can be translated as : How to replace array A values with values of array B in which A values are B keys?

Answer

Try this -

foreach($result['cities'] as $key => $cityInfo){
  list($city, $country) = explode($cityInfo);
  if(isset($asso[$country])){
    $newArr[$key] = $asso[$country];
  }
}