PHP multidimensional array search by value

前端 未结 23 3333
情歌与酒
情歌与酒 2020-11-21 04:45

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

<
23条回答
  •  野性不改
    2020-11-21 05:50

    If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.

    If you want just one result:

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

    For multiple results

    $keys = array_keys(array_column($userdb, 'uid'), 40489);
    

    In case you have an associative array as pointed in the comments you could make it with:

    $keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
    

    If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!

    Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!

提交回复
热议问题