如何在一个数组中按顺序找到与另一个数组匹配的值?
这是我的代码,它给了我与预期结果不对应的 $Array 4(如下所示):
<?php
for ($j=0; $j < 1; $j++) {
for ($i=0; $i < 100; $i++) {
$Array3 = (array_intersect($Array2, $Array1));
$Array4 = array_unique($Array3);
}
print_r($Array4);
}
?>
$Array 1 :
[not] => G
[have] => L
$Array 2 - 与 $Array 1 匹配的数组:
[Once] => B
[uppon] => A
[a] => G
[time] => M
[,] => Z
[a] => V
[small] => G
[squirrel] => F
[,] => Z
[whitch] => U
[once] => L
[in] => N
[the] => N
[forest] => X
[,] => Z
[set] => G \Search
[out] => L \string
[to] => V
[find] => M
[something] => N
[to] => W
[eat] => X
[,] => Z
[to] => G
[survive] => G
[.] => Z
我的代码的结果:
$Array 3 - 有重复项:
[a] => G
[small] => G
[once] => L
[set] => G \Search
[out] => L \string
[to] => G
$Array 4 - 结果(问题是"a"和"once"在数组中不相互跟随$Array 2):
[a] => G
[once] => L
预期结果:
[set] => G \Search
[out] => L \string
希望这可以满足您的需求。
function findSameInPosition($needle, $haystack) {
$indexedNeedle = array_values($needle);
$indexedHaystack = array_values($haystack);
foreach (array_keys($indexedHaystack) as $key) {
if (array_slice($indexedHaystack, $key, count($indexedNeedle)) === $indexedNeedle) {
return array_slice($haystack, $key, count($indexedNeedle));
}
}
}
// Example:
$input1 = array(
"not" => "G",
"have" => "L"
);
$input2 = array(
"Once" => "B",
"uppon" => "A",
"a" => "G",
"time" => "M",
"," => "Z",
"a" => "V",
"small" => "G",
"squirrel" => "F",
"," => "Z",
"whitch" => "U",
"once" => "L",
"in" => "N",
"the" => "N",
"forest" => "X",
"," => "Z",
"set" => "G",
"out" => "L",
"to" => "V",
"find" => "M",
"something" => "N",
"to" => "W",
"eat" => "X",
"," => "Z",
"to" => "G",
"survive" => "G",
"." => "Z"
);
findSameInPosition($input1, $input2); // Returns Array ( [set] => G [out] => L )