且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 多维数组按值搜索

更新时间:2023-02-23 09:38:06

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

重要的是要知道,如果您使用 === 运算符,则比较类型必须完全相同,在此示例中,您必须搜索 string 或仅使用== 代替 ===.

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 ===.

基于 angoru 的回答.在 PHP 的更高版本(>= 5.5.0)中,您可以使用单行.

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

这里是文档:http://php.net/manual/en/function.array-column.php.