PHP数组,获取基于一个值的键
发布时间:2020-12-13 16:39:26 所属栏目:PHP教程 来源:网络整理
导读:如果我有这个数组 $england = array( 'AVN' = 'Avon','BDF' = 'Bedfordshire','BRK' = 'Berkshire','BKM' = 'Buckinghamshire','CAM' = 'Cambridgeshire','CHS' = 'Cheshire'); 我想要能够从全文版本获取三个字母的代码,我将如何编写以下函数: $text_input
|
如果我有这个数组
$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;
}
谢谢!
使用
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]),以确保已发送有效的代码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
