PHP访问值使用不区分大小写的索引

Was*_* A. 1 php arrays indexing

如何使用不区分大小写的索引访问php数组中的值.喜欢

$x = array('a'=>'ddd');
Run Code Online (Sandbox Code Playgroud)

任何使用$ x ['A']访问它的函数;

Pas*_*TIN 6

在PHP中,这不是字符串/数组的工作方式.

在PHP中,"a"并且"A"是两个不同的字符串.
数组键是整数或字符串.

所以,$a["a"]$a["A"]指向数组中的两个不同的条目.


您有两种可能的解决方案:

  • 要么总是使用小写(或大写)键 - 这可能是最好的解决方案.
  • 或者在每个数组中搜索可能的匹配键,每次你想要访问一个条目 - 这是一个糟糕的解决方案,因为你必须循环(平均)一半的数组,而不是快速访问按键.


在第一种情况下,strtolower()每次要访问数组项时都必须使用:

$array[strtolower('KEY')] = 153;
echo $array[strtolower('KEY')];
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,像这样的mabe可能会起作用:(
嗯,这是一个未经过测试的想法;但它可能会以你为基础)

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这又是一个糟糕的解决方案!