簡體   English   中英

如果輸入的數據是鍵或值,則從關聯數組檢查並返回鍵

[英]checking and returning key from associative array if entered data is a key OR value

我從無法控制的數據庫中獲取信息。 “狀態”的值是用戶輸入(並正確清除)的值,但可以是寫出的狀態名稱或兩個字母的郵政縮寫。 我可以輕松地建立狀態和縮寫的關聯數組。 但是我在想,PHP是否可以確定狀態數組中的值是還是 因此,如果您輸入“ CA”,它將看到它是一個有效的兩個字母的密鑰並返回。 如果看到“XY”不是一個有效的 ,然后它retuns一個默認的“其他”鍵(ZZ),但如果用戶輸入的輸入為“紐約”,它會看到它是一個有效的 ,並返回相關的關鍵,“ NY“?

$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.
}

編輯:我已經更改了循環,以使其在一種情況下對照縮寫和完整狀態名稱檢查用戶輸入,而不是將它們分開。

用狀態和縮寫組成一個數組:

$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"
}
$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";

}
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!';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM