问题描述
我有一个数组内的数组。
I have an array within an array.
$a = array ( 0 => array ( 'value' => 'America', ), 1 => array ( 'value' => 'England', ), )
我如何检查是否'美'在数组中的存在?美洲阵列可以是任意键,并有可能是任何数量的子阵列,这样一个广义的解决方案吧。
How do I check if 'America' exists in the array? The America array could be any key, and there could be any number of subarrays, so a generalized solution please.
找上了PHP手册我看到in_array,但只适用于顶层。所以像 in_array(美国制造,$ A)
是行不通的。
Looking on the php manual I see in_array, but that only works for the top layer. so something like in_array("America", $a)
would not work.
感谢。
推荐答案
一个通用的解决方案是:
A general solution would be:
function deep_in_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && deep_in_array($needle, $element))
return true;
}
return false;
}
为什么我选择使用的原因 in_array
和的循环是:之前我检查阵列结构的更深层次的,我保证,该搜索到的值是不是在目前的水平。这样的话,我希望code要快于做某种的深度优先的搜索方法。
The reason why I chose to use in_array
and a loop is: Before I examine deeper levels of the array structure, I make sure, that the searched value is not in the current level. This way, I hope the code to be faster than doing some kind of depth-first search method.
当然,如果您的数组始终是二维的,只想在这样的阵列进行搜索,那么这是更快:
Of course if your array is always 2 dimensional and you only want to search in this kind of arrays, then this is faster:
function in_2d_array($needle, $haystack) {
foreach($haystack as $element) {
if(in_array($needle, $element))
return true;
}
return false;
}
这篇关于PHP检查是否在数组的数组存在价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!