PHP:在数组中查找数组序列
我一直在寻找一个函数,该函数在一个数组中搜索另一个数组,但没有找到一个函数,我决定编写它。我要寻找的是一个采用较小数组并在较大数组中搜索项目的确切顺序的函数。碰巧的是,PHP确实具有许多数组搜索功能,但是它们没有产生正确的结果。
该array_search()函数的确接受一个数组作为要搜索的针,但这将进行多维搜索。我也看到了一些使用array_intersect()或的 技术array_diff(),尽管这些函数能够在另一个数组中找到一个数组,但我对序列很感兴趣。
该函数的实现包含两个循环,一个循环通过干草堆数组,一个循环为针数组。如果找到的匹配数等于针阵列中的项数,则该函数返回true。
这是sequence_in_array()功能。
/**
* Determines if an array is part of another array.
*
* @param array $needle
* The array to search for.
* @param array $haystack
* The array to search in.
*
* @return bool
* True if the needle array is completely found in the haystack array.
*/
function sequence_in_array(array $needle, array $haystack) {
$haystackCount = count($haystack);
$needleCount = count($needle);
if ($needleCount > $haystack) {
throw new InvalidArgumentException('$needle array must be smaller than $haystack array.');
}
for ($i = 0; $i <= $haystackCount - $needleCount; $i++) {
$matchCount = 0;
for ($j = 0; $j < $needleCount; $j++) {
if ($needle[$j] == $haystack[$i + $j]) {
$matchCount++;
if ($matchCount == $needleCount) {
return TRUE;
}
}
}
}
return FALSE;
}为了对此进行测试,我建立了一个phpunit测试类,并使用dataProvider测试了一些不同的数组。这只是使用不同的数组重复调用该函数,并确保其正常工作。
/**
* @dataProvider arrayData
*/
public function testSequenceInArray($needle, $haystack, $expectedResult)
{
$result = sequence_in_array($needle, $haystack);
$this->assertEquals($expectedResult, $result);
}
public function arrayData() {
return [
[[], [], FALSE,],
[[7,8,9], [1,2,3,4,5,6], FALSE,],
[[1,3,4], [1,2,3,4,5,6], FALSE,],
[[1,4,3], [1,2,3,4,5,6], FALSE,],
[[1,2,3,9], [1,2,3,4,5,6], FALSE,],
[[1], [1,2,3,4,5,6], TRUE,],
[[1], [1], TRUE,],
[[1,2,3], [1,2,3,4,5,6], TRUE,],
[[3,4,5], [1,2,3,4,5,6], TRUE,],
[[4,5,6], [1,2,3,4,5,6], TRUE,],
[[1,2,3,4,5,6], [1,2,3,4,5,6], TRUE,],
[[42,43,44,45,46,47], range(1, 100), TRUE,],
];
}由于在搜索时无法找到这样的功能,因此希望它对某人有用。