Wwwebber's Blog

Hashmap based on values of a key based array

Posted in free php scripts, hashmap, job search script, sorting arrays by wwwebber on May 26, 2009
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”
);
</code>
and turn it into

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

function createHashMap(&$mc){
$hashMap = array();

while ($name = current($mc)) {
$key = key($mc);
//echo “key: $key , current:  “. $name . ‘ <br />’;
if(isset($name,$hashMap)){
//            $newKey = substr($key,0,strlen($key)-1) //remove last
$hashMap[“‘”. $name .”‘”] .= $key .’,’ ;
}
else{
$hashMap[“‘”. $name .”‘”] = “‘”. trim($key) .”‘”  ;
}
next($mc);
}

//print em out
foreach($hashMap as $key => $value)
echo $key . ‘ => ‘ . $value . ‘<br />’;
}

createHashMap($before);

Advertisements

Comments Off on Hashmap based on values of a key based array