对关联数组键进行分组 - 按相同顺序排列

时间:2009-10-29 07:23:50

标签: php arrays

我有以下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
);

技巧是我需要在正确的位置/顺序中根据它之前/之后插入任何独特的东西。 感谢

1 个答案:

答案 0 :(得分:2)

一般来说,你想要的是一个非平凡的算法。它被称为序列匹配或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);