如果输入的数据是键OR值,则检查并从关联数组返回键

时间:2012-07-08 09:16:34

标签: php arrays key-value

我从数据库中获取无法控制的信息。 “state”的值是用户输入(并且已正确清理)的值,但可以是写出的州名或两个字母的邮政缩写。我可以轻松地建立一个状态和缩写的关联数组。但我想知道是否有一种方法,PHP,以确定一个值是在state / abbrev数组中是否为。因此,如果您输入“CA”,它会看到它是一个有效的两个字母并返回它。如果它看到“XY”不是有效的,那么它会返回默认的“OTHER”键(ZZ),但如果用户输入的输入是“纽约”,它将看到它是有效的< strong> value 并返回关联的密钥“NY”?

4 个答案:

答案 0 :(得分: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.
}

编辑:我已经更改了循环,以便在一个条件下检查用户输入与缩写和完整状态名称,而不是将它们分开。

答案 1 :(得分: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"
}

答案 2 :(得分: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";

}

答案 3 :(得分:-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!';
}