PHP multidimensional array search by value

前端 未结 23 3327
情歌与酒
情歌与酒 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:40

    function searchForId($id, $array) {
       foreach ($array as $key => $val) {
           if ($val['uid'] === $id) {
               return $key;
           }
       }
       return null;
    }
    

    This will work. You should call it like this:

    $id = searchForId('100', $userdb);
    

    It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

    Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

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

    Here is documentation: http://php.net/manual/en/function.array-column.php.

提交回复
热议问题