douping3860 2017-05-20 14:25
浏览 97

使用array_search()返回与搜索字符串不匹配的第一个元素的键

If there is a way by which array_search() would return key of its first conflict like if I run

$key = array_search(40489, array_column($userdb, 'uid'));

on

Array
(

    (1) => Array
        (
            (uid) => '5465',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (uid) => '40489',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

it would ideally return

2

but I want it to return

1

i.e the first element that did not have the 'uid' = 40489 &

If its not possible with array_search() is there any other way to do it with loops? I tried array_filter() but can't get it to work.

  • 写回答

1条回答 默认 最新

  • droxlzcgnr639823 2017-05-20 14:35
    关注

    As said in array_search description:

    Searches the array for a given value and returns the first corresponding key if successful

    Returns the key for needle if it is found in the array, FALSE otherwise.

    So, you cannot use array_search to search something that not equals what you need. Instead write you own function, for example:

    $array = [];    // your array
    foreach ($array as $key => $value) {
        if ($value['uid'] != '40489') {
            echo 'Key: ', $key;
            // use `break` to stop iterating over 
            // array as you already found what you need
            break;
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答