php 检查多维数组的任何子数组中的特定键处是否存在特定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6990855/
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
Check if a specific value exists at a specific key in any subarray of a multidimensional array
提问by Rob
I need to search a multidimensional array for a specific value in any of the indexed subarrays.
我需要在多维数组中搜索任何索引子数组中的特定值。
In other words, I need to check a single column of the multidimensional array for a value. If the value exists anywhere in the multidimensional array, I would like to return true
otherwise false
换句话说,我需要检查多维数组的单个列中的值。如果该值存在于多维数组中的任何位置,我想true
否则返回false
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
I would like to know the fastest and most efficient way to check if the array $my_array
contains a value with the key "id". For example, if id => 152
anywhere in the multidimensional array, I would like true
.
我想知道检查数组是否$my_array
包含键为“id”的值的最快和最有效的方法。例如,如果id => 152
在多维数组中的任何位置,我都希望true
.
回答by Dan Grossman
Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.
没有什么比简单的循环更快的了。您可以混合和匹配一些数组函数来执行此操作,但它们也只会作为循环实现。
function whatever($array, $key, $val) {
foreach ($array as $item)
if (isset($item[$key]) && $item[$key] == $val)
return true;
return false;
}
回答by Friendly Code
Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):
这是 Dan Grossman 答案的更新版本,它将迎合多维数组(我所追求的):
function find_key_value($array, $key, $val)
{
foreach ($array as $item)
{
if (is_array($item) && find_key_value($item, $key, $val)) return true;
if (isset($item[$key]) && $item[$key] == $val) return true;
}
return false;
}
回答by Manuel Pardo
** PHP >= 5.5
** PHP >= 5.5
simply u can use this
只是你可以使用这个
$key = array_search(40489, array_column($userdb, 'uid'));
Let's suppose this multi dimensional array:
让我们假设这个多维数组:
$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'
)
);
$key = array_search(40489, array_column($userdb, 'uid'));
回答by stewe
If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:
如果您必须进行大量“id”查找并且它应该非常快,您应该使用包含所有“id”作为键的第二个数组:
$lookup_array=array();
foreach($my_array as $arr){
$lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:
现在您可以非常快速地检查现有 ID,例如:
echo (isset($lookup_array[152]))?'yes':'no';
回答by Jazzer
The simplest way is this:
最简单的方法是这样的:
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
if (array_search(152, array_column($my_array, 'id')) !== FALSE)
echo 'FOUND!';
else
echo 'NOT FOUND!';
回答by Anant
As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-
正如你的问题,这实际上是一个简单的二维数组不是更好吗?看一看-
Let say your 2-D array name $my_array and value to find is $id
假设您的二维数组名称 $my_array 和要查找的值是 $id
function idExists($needle='', $haystack=array()){
//now go through each internal array
foreach ($haystack as $item) {
if ($item['id']===$needle) {
return true;
}
}
return false;
}
and to call it:
并称之为:
idExists($id, $my_array);
As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value
正如你所看到的,它实际上只检查是否有任何只有 key_name 'id' 的内部索引,有你的 $value。如果 key_name 'name' 也有 $value,这里的其他一些答案也可能会导致 true
回答by Imran Qamer
A good solution can be one provided by @Elias Van Ootegan
in a comment that is:
一个好的解决方案可以@Elias Van Ootegan
在评论中提供,即:
$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";
I tried it and worked for me, thanks buddy.
我试过了并为我工作,谢谢伙计。
Edited
已编辑
Note: It will work in PHP 5.5+
注意:它适用于 PHP 5.5+
回答by amphetamachine
TMTOWTDI. Here are several solutions in order of complexity.
TMTOWTDI。以下是按复杂程度排序的几种解决方案。
(Short primer on complexity follows):O(n)
or "big o" means worstcase scenario where n
means the number of elements in the array, and o(n)
or "little o" means bestcase scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2
or n!
. It's more a measure of change in computing time as n
increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.
(关于复杂性的简短入门):O(n)
或“大 o”表示最坏的情况,其中n
表示数组中的元素数量,o(n)
或“小 o”表示最好的情况。长离散数学故事短,你真的只需要担心最坏的情况,并确保它不是n ^ 2
或n!
。它更多地是衡量计算时间随着n
增加而变化的量度,而不是整体计算时间。维基百科有一篇关于计算又名时间复杂度的好文章。
If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.
如果经验教会了我什么,那就是花太多时间优化你的程序的 little-o 明显是浪费时间,最好花在做某事 - 任何 - 更好的事情上。
Solution 0: O(n) / o(1)
complexity:
解决方案 0:O(n) / o(1)
复杂性:
This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.
此解决方案的最佳情况是 1 次比较 - 1 次循环迭代,但前提是匹配值位于数组的位置 0 中。最坏的情况是它不在数组中,因此必须遍历数组的每个元素。
foreach ($my_array as $sub_array) {
if (@$sub_array['id'] === 152) {
return true;
}
}
return false;
Solution 1: O(n) / o(n)
complexity:
解决方案 1:O(n) / o(n)
复杂性:
This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n
iterations thru the array.
无论匹配值在哪里,此解决方案都必须循环遍历整个数组,因此它始终是n
遍历数组的迭代。
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Solution 2: O(n log n) / o(n log n)
complexity:
解决方案2:O(n log n) / o(n log n)
复杂性:
A hash insertion is where the log n
comes from; n
hash insertions = n * log n
. There's a hash lookup at the end which is another log n
but it's not included because discrete match.
哈希插入是从哪里来的log n
;n
哈希插入 = n * log n
。最后有一个散列查找,这是另一个log n
但不包括在内,因为离散匹配。
$existence_hash = [];
foreach ($my_array as $sub_array) {
$existence_hash[$sub_array['id']] = true;
}
return @$existence_hash['152'];
回答by marcnyc
I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).
我找到了这篇文章,希望做同样的事情,并想出了我自己的解决方案,我想为这个页面的未来访问者提供(并看看这样做是否会出现我没有预见到的任何问题)。
If you want to get a simple true
or false
output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos
to search for the value:
如果你想得到一个简单的true
orfalse
输出,并想用一行代码来做这件事,没有函数或循环,你可以序列化数组,然后用它stripos
来搜索值:
stripos(serialize($my_array),$needle)
stripos(serialize($my_array),$needle)
It seems to work for me.
它似乎对我有用。
回答by Faisal
Try with this below code. It should be working fine for any kind of multidimensional array search.
尝试使用以下代码。它应该适用于任何类型的多维数组搜索。
Here you can see LIVE DEMO EXAMPLE
在这里你可以看到现场演示示例
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ( ($element === $search_for) ){
return true;
}elseif(is_array($element)){
$result = multi_array_search($search_for, $element);
if($result == true)
return true;
}
}
return false;
}