PHP: Check if array contains another array values (in specific order)
我有一个数组:
如果我检查草堆里是否有针的话,我就得说实话。但如果我检查草堆里是否有坏针,我也需要假针。所有草垛和针的尖端都没有前臂?
1 2 3 4 5 | $offset = array_search($needle[0], $haystack); $slice = array_slice($haystack, $offset, count($needle)); if ($slice === $needle) { // yes, contains needle } |
但如果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $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 } |
1 2 3 |
一个工作数组的slice()仍然需要一个循环,我可以计算出:
1 2 3 4 5 6 | foreach(array_keys($haystack, reset($needle)) as $offset) { if($needle == array_slice($haystack, $offset, count($needle))) { // yes, contains needle break; } } |