PHP访问值使用不区分大小写的索引 [英] PHP access value using case insensitive index
问题描述
如何使用不区分大小写的索引访问php数组中的值。
like
how to access a value in php array using case insensitive index. like
$x = array('a'=>'ddd');
使用$ x ['A']访问它的任何函数;
any function to access it using $x['A'];
推荐答案
这不是字符串/数组在PHP中的工作方式。
That is just not the way strings / array work, in PHP.
在PHP中, a
和A
是两个不同的字符串。
数组键是整数或字符串。
In PHP, "a"
and "A"
are two different strings.
Array keys are either integers or strings.
所以, $ a [a]
和 $ a [A]
指向数组中的两个不同条目。
So, $a["a"]
and $a["A"]
point to two distinct entries in the array.
您有两种可能的解决方案:
You have two possible solutions :
- 要么总是使用小写(或大写)键 - 这可能是最好的解决方案。
- 或者在每次要访问条目时搜索所有数组中的可能匹配键 - 这是一个糟糕的解决方案,因为你必须循环遍历(平均值)数组的一半,而不是通过密钥快速访问。
- Either always using lower-case (or upper-case) keys -- which is probably the best solution.
- Or search through all the array for a possible matching key, each time you want to access an entry -- which is a bad solution, as you'll have to loop over (in average) half the array, instead of doing a fast access by key.
在第一种情况下,你必须使用 <$ c每次要访问数组项时,$ c> strtolower() :
$array[strtolower('KEY')] = 153;
echo $array[strtolower('KEY')];
在第二种情况下,mabe这样的东西可能会起作用:
(嗯,这是一个未经过测试的想法;但它可能会以你为基础)
In the second case, mabe something like this might work :
(Well, this is a not-tested idea ; but it might serve you as a basis)
if (isset($array['key'])) {
// use the value -- found by key-access (fast)
}
else {
// search for the key -- looping over the array (slow)
foreach ($array as $upperKey => $value) {
if (strtolower($upperKey) == 'key') {
// You've found the correct key
// => use the value
}
}
}
但是,再次这是一个糟糕的解决方案!
But, again it is a bad solution !
这篇关于PHP访问值使用不区分大小写的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!