在数组搜索连续值 [英] Searching for consecutive values in an array

查看:112
本文介绍了在数组搜索连续值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是在一个阵列搜索连续值的最佳方法?

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;
}

这篇关于在数组搜索连续值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆