PHP:检查数组是否包含另一个数组值(按特定顺序)


PHP: Check if array contains another array values (in specific order)

我有一个数组:

$haystack = array(1,2,3,4,5,6,7,8,9,10...);
$needle = array(3,4,5);
$bad_needle = array(3,5,4);

如果我检查干草堆是否包含针,我需要得到真。但是如果我检查大海捞针是否包含bad_needle,我也需要。所有干草堆和针头都没有小费?

$offset = array_search($needle[0], $haystack);
$slice  = array_slice($haystack, $offset, count($needle));
if ($slice === $needle) {
    // yes, contains needle
}

但是,如果$haystack中的值不唯一,则此操作将失败。在这种情况下,我会使用一个很好的循环:

$found  = false;
$j      = 0;
$length = count($needle);
foreach ($haystack as $i) {
    if ($i == $needle[$j]) {
        $j++;
    } else {
        $j = 0;
    }
    if ($j >= $length) {
        $found = true;
        break;
    }
}
if ($found) {
    // yes, contains needle
}
var_dump(strpos(implode(',', $haystack), implode(',', $needle)) !== false);
var_dump(strpos(implode(',', $haystack), implode(',', $bad_needle)) !== false);

我所能计算的那样,一个有效的 array_slice() 仍然需要一个循环:

foreach(array_keys($haystack, reset($needle)) as $offset) {
    if($needle == array_slice($haystack, $offset, count($needle))) {
        // yes, contains needle
        break;
    }
}