PHP:数组键的情况下不区分大小写* *查找? [英] php: Array keys case *insensitive* lookup?
问题描述
$myArray = array ('SOmeKeyNAme' => 7);
我想 $ myArray的['somekeyname']
返回 7
。结果
有没有办法做到这一点,没有操纵数组?
I want $myArray['somekeyname']
to return 7
.
Is there a way to do this, without manipulating the array?
我不创建磁盘阵列,这样一个无法控制它的键
I don't create the array, an thus can not control it's keys
推荐答案
您不能没有任何线性搜索或改变原始数组做到这一点。最有效的方法将是使用上的按键用strtolower 当您插入,当你查找值。
Option 1 - change the way you create the array
You can't do this without either a linear search or altering the original array. The most efficient approach will be to use strtolower on keys when you insert AND when you lookup values.
$myArray[strtolower('SOmeKeyNAme')]=7;
if (isset($myArray[strtolower('SomekeyName')]))
{
}
如果重要的是要你preserve的关键原来如此,你可以将它保存为该键的附加价值,例如
If it's important to you to preserve the original case of the key, you could store it as a additional value for that key, e.g.
$myArray[strtolower('SOmeKeyNAme')]=array('SOmeKeyNAme', 7);
选项2 - 创建一个辅助映射
当你更新的问题表明这不会对你是不可能的,你怎么样建立一个数组小写和大小写敏感的版本之间提供映射?
Option 2 - create a secondary mapping
As you updated the question to suggest this wouldn't be possible for you, how about you create an array providing a mapping between lowercased and case-sensitive versions?
$keys=array_keys($myArray);
$map=array();
foreach($keys as $key)
{
$map[strtolower($key)]=$key;
}
现在,你可以用它来获取区分大小写键小写有一个
Now you can use this to obtain the case-sensitive key from a lowercased one
$test='somekeyname';
if (isset($map[$test]))
{
$value=$myArray[$map[$test]];
}
这避免了需要创建数组的完整副本与套管下键,这实在是唯一的其他方式来进行此事。
This avoids the need to create a full copy of the array with a lower-cased key, which is really the only other way to go about this.
如果使阵列的完整副本不是问题,那么你可以使用在array_change_key_case 以较低的套管键创建一个副本
If making a full copy of the array isn't a concern, then you can use array_change_key_case to create a copy with lower cased keys.
$myCopy=array_change_key_case($myArray, CASE_LOWER);
这篇关于PHP:数组键的情况下不区分大小写* *查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!