PHP多维数组按值搜索 [英] PHP multidimensional array search by value
问题描述
我有一个数组,我想在其中搜索uid
并获取该数组的键.
I have an array where I want to search the uid
and get the key of the array.
假设我们有以下二维数组:
Assume we have the following 2-dimensional array:
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
函数调用search_by_uid(100)
(第一个用户的uid)应返回0
.
The function call search_by_uid(100)
(uid of first user) should return 0
.
函数调用search_by_uid(40489)
应该返回2
.
我尝试进行循环,但是我想要更快的执行代码.
I tried making loops, but I want a faster executing code.
推荐答案
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/zh/function.array-column.php .
这篇关于PHP多维数组按值搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!