2010-12-02 99 views
9

如果我有这样的阵列PHP阵列,获得基于值的键

$england = array(
     'AVN' => 'Avon', 
     'BDF' => 'Bedfordshire', 
     'BRK' => 'Berkshire', 
     'BKM' => 'Buckinghamshire', 
     'CAM' => 'Cambridgeshire', 
     'CHS' => 'Cheshire' 
); 

我希望能够从全文版本获得的三个字母代码,如何将我写了以下功能:

$text_input = 'Cambridgeshire'; 
function get_area_code($text_input){ 
    //cross reference array here 
    //fish out the KEY, in this case 'CAM' 
    return $area_code; 
} 

谢谢!

回答

25

使用array_search()

$key = array_search($value, $array); 

所以,在你的代码:

// returns the key or false if the value hasn't been found. 
function get_area_code($text_input) { 
    global $england; 
    return array_search($england, $text_input); 
} 

如果你想它不区分大小写,您可以使用此功能,而不是array_search()

function array_isearch($haystack, $needle) { 
    foreach($haystack as $key => $val) { 
     if(strcasecmp($val, $needle) === 0) { 
      return $key; 
     } 
    } 
    return false; 
} 

如果你的数组值是正则表达式,你可以使用这个函数:

function array_pcresearch($haystack, $needle) { 
    foreach($haystack as $key => $val) { 
     if(preg_match($val, $needle)) { 
      return $key; 
     } 
    } 
    return false; 
} 

在这种情况下,您必须确保数组中的所有值都是有效的正则表达式。

但是,如果值来自<input type="select">,则有更好的解决方案: 而不是<option>Cheshire</option>使用<option value="CHS">Cheshire</option>。然后,表单将提交指定的值而不是显示的名称,您将不必在数组中进行任何搜索;您只需检查isset($england[$text_input])以确保已发送有效的代码。

+2

+1 @Haroldo清楚,使用字符串时array_search是区分大小写的。 – SubniC 2010-12-02 11:50:28

+0

是否有可能做array_seach,其中的值是一个正则表达式?然后,我可以使用preg_quote和帐户的缩写和不同版本的... ... – Haroldo 2010-12-02 11:54:51

6

如果$england所有的值都是独一无二的,你可以这样做:

$search = array_flip($england); 
$area_code = $search['Cambridgeshire'];