PHP 多维数组按值搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6661530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP multidimensional array search by value
提问by Rachit
I have an array where I want to search the uid
and get the key of the array.
我有一个数组,我想在其中搜索uid
并获取数组的键。
Examples
例子
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'
)
);
The function call search_by_uid(100)
(uid of first user) should return 0
.
函数调用search_by_uid(100)
(第一个用户的 uid)应该返回0
.
The function call search_by_uid(40489)
should return 2
.
函数调用search_by_uid(40489)
应该返回2
。
I tried making loops, but I want a faster executing code.
我尝试制作循环,但我想要更快的执行代码。
回答by Jakub Trune?ek
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 ===
.
重要的是要知道,如果您使用===
运算符比较类型必须完全相同,在此示例中您必须搜索string
或仅使用==
替代===
。
Based on angoruanswer. In later versions of PHP (>= 5.5.0
) you can use one-liner.
基于angoru答案。在 PHP ( >= 5.5.0
) 的更高版本中,您可以使用单行。
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
回答by angoru
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.
如果您使用的是 (PHP 5 >= 5.5.0),则不必编写自己的函数来执行此操作,只需编写此行即可。
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!
如果你使用的是 PHP < 5.5.0,你可以使用这个 backport,谢谢 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!
更新:我一直在做一些简单的基准测试,多结果表单似乎是最快的,甚至比 Jakub 自定义函数还要快!
回答by Iryna Batvina
In later versions of PHP (>= 5.5.0) you can use this one-liner:
在更高版本的 PHP (>= 5.5.0) 中,您可以使用这个单行:
$key = array_search('100', array_column($userdb, 'uid'));
回答by reflexiv
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
基于 Jakub 的优秀答案,这里有一个更通用的搜索,它将允许指定密钥(不仅仅是 uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Usage: $results = searcharray('searchvalue', searchkey, $array);
用法: $results = searcharray('searchvalue', searchkey, $array);
回答by amurrell
I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.
我知道这已经得到了回答,但是我使用了它并在我的代码中对其进行了更多扩展,这样您就不会仅通过 uid 进行搜索。我只想将它分享给可能需要该功能的任何其他人。
Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
这是我的例子,请记住这是我的第一个答案。我取出了 param 数组,因为我只需要搜索一个特定的数组,但您可以轻松地将其添加进去。我想搜索的不仅仅是 uid。
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
此外,在我的情况下,由于搜索可能不唯一的其他字段,可能会返回多个键。
/**
* @param array multidimensional
* @param string value to search for, ie a specific field name like name_first
* @param string associative key to find it in, ie field_name
*
* @return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
后来,我最终写了这个,让我可以搜索另一个值和关联键。因此,我的第一个示例允许您在任何特定关联键中搜索一个值,并返回所有匹配项。
This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) ANDanother value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).
第二个示例显示在某个关联键 (first_name) 中找到值 ('Taylor') 的位置和在另一个关联键 (已使用) 中找到另一个值 (true) 的位置,并返回所有匹配项(具有名字的人的键) 'Taylor' AND 被雇用)。
/**
* @param array multidimensional
* @param string $search_value The value to search for, ie a specific 'Taylor'
* @param string $key_to_search The associative key to find it in, ie first_name
* @param string $other_matching_key The associative key to find in the matches for employed
* @param string $other_matching_value The value to find in that matching associative key, ie true
*
* @return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Use of function
函数的使用
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Result
结果
Array ( [0] => 2 )
回答by BEJGAM SHIVA PRASAD
Looks array_filterwill be suitable solution for this...
看起来array_filter将是合适的解决方案......
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
PHP Code
PHP代码
<?php
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH) // With latest PHP third parameter is mandatory.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$values= print_r(array_value($found));
$keys = print_r(array_keys($found));
回答by voodoo417
I modified one of examples below description function array_search. Function searchItemsByKey
return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:
我修改了下面描述函数array_search的示例之一。函数searchItemsByKey
通过 $key 从多维数组(N 级)返回所有值。也许,这对某人有用。例子:
$arr = array(
'XXX'=>array(
'YYY'=> array(
'AAA'=> array(
'keyN' =>'value1'
)
),
'ZZZ'=> array(
'BBB'=> array(
'keyN' => 'value2'
)
)
//.....
)
);
$result = searchItemsByKey($arr,'keyN');
print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
[0] => value1
[1] => value2
)
Function code:
功能代码:
function searchItemsByKey($array, $key)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key)
$results[] = $array[$key];
foreach ($array as $sub_array)
$results = array_merge($results, searchItemsByKey($sub_array, $key));
}
return $results;
}
回答by Rahul
Here is one liner for the same,
这是一个相同的衬垫,
$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];
回答by Angry 84
Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.
尽管这是一个老问题并且有一个可接受的答案,但我想我会建议对已接受的答案进行一次更改..所以首先,我同意这里接受的答案是正确的。
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if ($val[$sKey] == $id) {
return $key;
}
}
return false;
}
Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.
用函数中的参数替换预设的“uid”,因此现在调用以下代码意味着您可以在多种数组类型中使用一个函数。微小的变化,但会产生细微的差异。
// Array Data Of Users
$userdb = array (
array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);
// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
echo "Search Result can not be found";
}
回答by M.suleman Khan
I want to check tha in the following array $arr
is there 'abc' exists in sub arrays or not
我想检查以下数组$arr
中的子数组中是否存在“abc”
$arr = array(
array(
'title' => 'abc'
)
);
Then i can use this
然后我可以使用这个
$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
echo 'exists';
} else {
echo 'notExists';
}
I think This is the Most simple way to define
我认为这是最简单的定义方式