【问题标题】:How to have value follow each other in PHP?如何在 PHP 中让值相互跟随?
【发布时间】:2017-05-17 23:15:47
【问题描述】:

如何在一个数组中找到与另一个数组按顺序匹配的值?

这是我的代码,它为我提供了与预期结果不对应的 $Array4(如下所示):

<?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);
}
?>

$Array1:

[not] => G
[have] => L

$Array2 - 与 $Array1 匹配的数组:

[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

我的代码的结果:

$Array3 - 重复:

[a] => G
[small] => G
[once] => L
[set] => G     \\Search 
[out] => L     \\string
[to] => G

$Array4 - 结果(问题是“a”和“once”在数组 $Array2 中不相互跟随):

[a] => G
[once] => L

预期结果:

[set] => G    \\Search 
[out] => L    \\string 

【问题讨论】:

  • 这是一个很奇怪的情况。即使你试过了,我觉得你没有设法解释你想要什么。我建议你提供Array1Array2 中的数据,然后提供你得到的结果和你想要得到的结果。不过,这可能只是我。
  • @Milailo Array1 & Array2 的数据总量如上所示。上面也给出了得到的结果和期望的结果。
  • $Array1 中的键 nothave 的用途是什么?

标签: php arrays array-unique array-intersect


【解决方案1】:

这有望满足您的需求。

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 )

【讨论】:

  • 非常感谢您的回答。但是,我不明白为什么当我更改数组中的值时,例如通过放置“V”“M”而不是“G”“L”,结果是这样的:[a] => V [time] => M 而应该是 [to] => V [find] => M ?
  • 那是因为一个数组不能有多个具有相同键的值。最后一个要定义的将覆盖之前定义的。如果这不适合您的需求,您将不得不使用另一个数据结构来拥有多个键。如果是这种情况,我鼓励您使用类似于以下答案中提到的数据结构提出一个新问题:stackoverflow.com/a/2879138/4493079
  • 谢谢 :) 这确实是一个问题,但我不能这样做......正是出于这个原因,我一直在寻找一个允许我获取确定值的系统,这些值在它们之间是固定的。 (y)
  • 好吧,那么我很遗憾地告诉您,您的问题没有解决方案。除非您可以创建一个具有如下结构的数组:array( array("Once" =&gt; "B"), array("uppon" =&gt; "A"), array("a" =&gt; "G") ) 等等。
猜你喜欢
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2022-10-15
  • 2014-08-23
  • 2017-07-13
相关资源
最近更新 更多