【问题标题】:Grouping associative array keys - in the same order分组关联数组键 - 以相同的顺序
【发布时间】:2009-10-29 07:23:49
【问题描述】:

我有以下 2 个数组并想将它们组合起来。我对键比对它们的值更感兴趣。我想拿这个

$arr1 = array(
  'tom' => "1", 
  'sally' => "20"   // unique
  'larry' => "2", 
  'kate' => "3",
  'dave' => "23"    //unique
);

$arr2 = array(
  'tom' => "11", 
  'larry' => "12", 
  'drummer' => "2", // unique
  'kate' => "7",
  'nick' => "3"     //unique
);

把它变成这样的东西

$arr = array(
  'tom',
  'sally',     //unique from arr1, ended up here because she's before larry
  'drummer',   //unique from arr2, ended up here because he's after larry
  'larry', 
  'kate',
  'dave',     //unique from arr1, ended up here because he's after the last 2 similar
  'nick'      //unique from arr2, ended up here because he's after the last 2 similar
);

诀窍是我需要根据之前/之后的内容在正确的位置/顺序中插入任何独特的内容。 谢谢

【问题讨论】:

  • 这个顺序对我来说没有意义。如果“drummer”在最终数组中的“larry”之后,那将是合乎逻辑且可实施的。在您的示例中,与原始数组相比,它们的顺序相反,这似乎相当随意。那么为什么“kate”之前不也是“nick”呢?
  • 哎呀,错字:) 将编辑。

标签: php arrays


【解决方案1】:

通常你想要的是一个非平凡的算法。它称为序列匹配或longest common subsequence problem。我不认为有一个内置的 PHP 函数来计算它。获得匹配项后,您可以处理它们之间的不匹配项。请注意,可以有多个公共子序列,因此如果您真的想要这种合并,所有项目的顺序并不总是与原始数组中的相同。

如果不需要最好的结果,您可以尝试这样的近似值,它会贪婪地在下一个 4 项内寻找匹配项:

$result = array();

$i = 0;
$j = 0;
while ($i < count($arr1)) {
    // Look for a matching item in the next four items of $arr2
    $k = 0;
    while ($k < 4) {
        // Do we have a match?
        if ($arr1[$i] == $arr2[$j+$k]) {
            // Add items from $arr2 that are before the matching item
            while ($k-- > 0) {
                $result[] = $arr2[$j];
                $j++;
            }
            $j++;
            break;
        }
        $k++;
    }
    // Add the current item fro $arr1
    $result[] = $arr1[$i];
    $i++;
}
// Add the remaining items from $arr2
while ($j < count($arr2)) {
    $result[] = $arr2[$j];
    $j++;
}

$result = array_unique($result);

【讨论】:

  • 由于某种原因,我的编辑/尝试没有显示在帖子中。可能需要一段时间才能显示已编辑的新内容。但你说的是对的,卢卡斯。鼓手现在按照逻辑预期在追捕拉里
  • 是的,这个答案是基于当前版本的。对于之前的订单,您仍然需要获得 LCS,但不匹配项目的顺序不会那么清楚。
  • 你有想法让我继续使用它。这不是绝对必要的功能,但如果拥有它会很好,所以我想为什么不尝试让它工作。我认为在我的情况下可能不需要 LCS。我在想通过第二个数组,看看有没有什么是独一无二的,然后尝试匹配它适合的地方。
猜你喜欢
  • 2019-06-15
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 2014-10-05
  • 2019-12-10
相关资源
最近更新 更多