Jump to content

Convert state to state abbreviation


rondog

Recommended Posts

I have a database with like 3000 entries that all have the full state name like "California"...I need to change all these to the abbreviated version like "CA".

 

Can someone help me come up with a script to just run once and have it update all the entries?

 

I already have an array of state info with both full name and abbreviation:

$states_arr  = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa",  'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'DC'=>"Washington D.C.",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");

Link to comment
https://forums.phpfreaks.com/topic/204601-convert-state-to-state-abbreviation/
Share on other sites

Make another array with the state names as the keys and the abbreviations as the values:

<?php
$states_abbr = array();
foreach ($states_arr as $abbr => $state) {
    $states_abbr[$state] = $abbr
}
?>

The simply retrieve each record  and use the $states_abbr array to get the correct abbreviation and update the record.

 

Ken

Update the table:

 

$case = '';
foreach ($states_arr as $country_code => $country_name) {
  $case .= "WHEN '$country_name' THEN '$country_code' ";
}

$query = "UPDATE table SET country_code = (CASE country_name $case END)";
echo $query;//check if query was properly constructed

 

Or use ken's solution to map states to their abbreviations at run-time.

I would have suggested.

 

$search_term = 'California';
$abbr = array_keys($states_arr,$search_term);
echo $abbr[0];

 

This would run at runtime, I don't know if I would change all of those columns.  If I wanted to input them into the Base, I would add a column.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.