Searching for consecutive values in an array

前端 未结 3 799
面向向阳花
面向向阳花 2021-01-23 17:04

What\'s the best way to search for consecutive values in an array?

For example, searching for array(\'a\', \'b\') in array(\'x\', \'a\', \'b\', \'c\

相关标签:
3条回答
  • 2021-01-23 17:17

    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;
    }
    
    0 讨论(0)
  • 2021-01-23 17:22

    This is probably sub-optimal but is fairly concise:

    $needle = array('a', 'b');
    $haystack = array('x', 'a', 'b', 'c');
    
    function searchInArray($haystack, $needle)
    {
        $keys = array_search($haystack, $needle[0]);
    
        foreach ($keys as $key) {
            $endPos = $key + count($needle);   
            for ($i=1; $i<$count($needle); $i++) {
                if ($needle[$i] == $haystack[$key + $i]) {
                    return $key;
                }
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2021-01-23 17:26

    This does what you're asking for, it's somewhat specific as all arrays must be non-keyed, and have unique values.

    Additionally, in this version the arrays can only contain integer or string values. If you need any NULL, object, float and arrays as well, a part of it needs to be changed from the array_flip() + isset() to array_search().

    CodePad / Gist

    The relevant part is to compare a slice of the array you search in (here $in) with the array you search for (here $for):

    array_slice($in, $pos, $len) === $for
    

    $pos has been looked up earlier for the first value of $for, $len is count($for).

    0 讨论(0)
提交回复
热议问题