我在一个数组中有一个数组.
$a = array ( 0 => array ( 'value' => 'America', ), 1 => array ( 'value' => 'England', ), )
Run Code Online (Sandbox Code Playgroud)
如何检查阵列中是否存在"America"?America数组可以是任何键,并且可以有任意数量的子数组,所以请使用通用解决方案.
看看php手册我看到in_array,但这只适用于顶层.所以像是in_array("America", $a)不行的.
谢谢.
Fel*_*ing 12
一般解决方案是:
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;
}
Run Code Online (Sandbox Code Playgroud)
我选择使用in_array 和循环的原因是:在我检查数组结构的更深层次之前,我确保搜索到的值不在当前级别.这样,我希望代码比做某种深度优先搜索方法更快.
当然,如果你的数组总是2维,你只想搜索这种数组,那么这个更快:
function in_2d_array($needle, $haystack) {
foreach($haystack as $element) {
if(in_array($needle, $element))
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
PHP没有本机array_search_recursive()功能,但您可以定义一个:
function array_search_recursive($needle, $haystack) {
foreach ($haystack as $value) {
if (is_array($value) && array_search_recursive($needle, $value)) return true;
else if ($value == $needle) return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
未经测试但你明白了.
| 归档时间: |
|
| 查看次数: |
14225 次 |
| 最近记录: |