duanhan3067 2010-11-21 19:56
浏览 17
已采纳

php:数组键案例*不敏感*查找?

$myArray = array ('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

  • 写回答

12条回答 默认 最新

  • duanraa1984 2010-11-21 19:59
    关注

    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')]))
     {
    
     }
    

    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);
    

    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.

    Option 3 - Create a copy of the array

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行