Monday, May 25, 2009

Hashmap based on values of a key based array

I recently had to create a function that would take the values in a key based array and create a hashmap based off of the values. Basically, I had to switch the keys and values. (Remember there are no duplicate keys and I was going to need multiple objects associated with 1 key..this was all part of my free php job search script ) . Anyway, the goal was to take an array like this


$before = array(
"White Plains" => "NY",
"New York City" => "NY",
"Philadelphia" =>"PA",
"Tampa" =>"FL",
"Miami" =>"FL"
);

and turn it into an array like this

$after = array('NY' => White Plains,New York City,
'PA' => Philadelphia,
'FL' => Tampa,Miami
)

Here's the function...enjoy
before = array( "White Plains" => "NY", "New York City" => "NY", "Philadelphia" =>"PA", "Tampa"   =>"FL", "Miami"   =>"FL" );  function createHashMap(&$mc){ $hashMap = array(); while ($name = current($mc)) {   $key = key($mc);   //echo "key: $key , current:  ". $name . '
'; if(isset($name,$hashMap)){ $hashMap["'". $name ."'"] .= $key .',' ; } else{ $hashMap["'". $name ."'"] = "'". trim($key) ."'" ; } next($mc); } //print em out foreach($hashMap as $key => $value) echo $key . ' => ' . $value . '
'; } createHashMap($before);



No comments: