问题描述
我需要在多维数组中搜索任何索引子数组中的特定值.
I need to search a multidimensional array for a specific value in any of the indexed subarrays.
换句话说,我需要检查多维数组的单个列中的值.如果该值存在于多维数组中的任何位置,我想返回true
,否则返回false
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
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
我想知道最快最有效的方法来检查数组$my_array
是否包含键为"id"的值.例如,如果id => 152
在多维数组中的任意位置,我想要true
.
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
.
推荐答案
没有什么比简单的循环要快的了.您可以混合匹配一些数组函数来实现,但是它们也将被实现为循环.
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;
}
这篇关于检查多维数组的任何子数组中的特定键处是否存在特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!