在数组搜索连续值
问题描述:
什么是在一个阵列搜索连续值的最佳方法?
What's the best way to search for consecutive values in an array?
例如,搜索阵列('A','B')
在阵列('X','A','B ','C')
将产生 1
,因为这些值:第一,指数出现在连续。
For example, searching for array('a', 'b')
in array('x', 'a', 'b', 'c')
would yield 1
, because the values first appear consecutively at that index.
答
没有测试过这一点,但这样的事情应该做的:
Haven't tested this, but something like this should do:
function consecutive_values(array $needle, array $haystack) {
$i_max = count($haystack)-count($needle);
$j_max = count($needle);
for($i=0; $i<$i_max; ++$i) {
$match = true;
for($j=0; $j<$j_max; ++$j) {
if($needle[$j]!=$haystack[$i+$j]) {
$match = false;
break;
}
}
if($match) {
return $i;
}
}
return -1;
}