我从一个我无法控制的数据库中获取信息。“状态”的值是用户输入(并正确清理)的值,但可能是写出的州名称或两个字母的邮政缩写。我可以轻松构建状态和缩写的关联数组。但我想知道是否有一种方法,PHP,可以确定一个值是否在 states/abbrev 数组中作为key OR a value。因此,如果您输入“CA”,它会看到它是一个有效的两个字母密钥并返回它。如果它看到“XY”不是一个有效的键,那么它会返回一个默认的“OTHER”键(ZZ),但是如果用户输入的输入是“New York”,它会看到它是一个有效的值并返回相关的键,“纽约”?
问问题
350 次
4 回答
3
$userInput; // Your user's input, processed using regex for capitals, etc to match DB values for the strings of the states.
// Otherwise, do your comparisons in the conditions within the loop to control for mismatching capitals, etc.
$output = false;
foreach ($stateArray as $abbreviation => $full) // Variable $stateArray is your list of Abbreviation => State Name pairs.
{
if ($userInput == $abbreviation || $userInput == $full) // Use (strtolower($userInput) == strtolower($abbreviation) || strtolower($userInput) == strtolower($full)) to change all the comparison values to lowercase.
// This is one example of processing the strings in a way to ensure some flexibility in the user input.
// However, whatever processing you need to do is determined by your needs.
{
$output = array($abbreviation => $full); // If you want a key => value pair, use this.
$output = $abbreviation; // If you only want the key, use this instead.
break;
}
}
if ($output === false)
{
$output = array("ZZ" => "OTHER"); // If you want a key => value pair, use this.
$output = "ZZ"; // If you only want the key, use this instead.
}
编辑:我已经更改了循环,以便它在一个条件下检查用户输入与缩写和完整状态名称,而不是将它们分开。
于 2012-07-08T09:37:24.250 回答
1
用状态和缩写创建一个数组:
$array = array("new york" => "ny", "california" => "ca", "florida" => "fl", "illinois" => "il");
检查输入:
$input = "nY";
if(strlen($input) == 2) // it's an abbreviation
{
$input = strtolower($input); // turns "nY" into "ny"
$state = array_search($input, $array);
echo $state; // prints "new york"
echo ucwords($state); // prints "New York"
}
// ----------------------------------------------------//
$input = "nEw YoRk";
if(strlen($input) > 2) // it's a full state name
{
$input = strtolower($input); // turns "nEw YoRk" into "new york"
$abbreviation = $array[$input];
echo $abbreviation; // prints "ny";
echo strtoupper($abbreviation); // prints "NY"
}
于 2012-07-08T09:29:49.720 回答
1
$array = array("New York" => "NY",
"California" => "CA",
"Florida" => "FL",
"Illinois" => "IL");
$incoming = "New York";
if( in_array($incoming, $array) || array_key_exists($incoming, $array)){
echo "$incoming is valid";
}
于 2012-07-08T09:37:53.183 回答
-1
if (!isset($array[$input]))
{
// swap it
$temp = array_flip($array);
if (isset($temp[$input]))
{
echo 'Got it as abbreviation!';
}
else
{
echo 'NO Match';
}
}
else
{
echo 'Got it as state!';
}
于 2012-07-08T09:37:29.143 回答