在两个数组之间添加/删除/更改key =>值对

时间:2013-09-12 17:21:31

标签: php arrays

我有两个名为$ old和$ new的多维数组。我想比较两个数组,看看在两者之间添加,删除或更改了k => v。

这些是数组:

$old = array(
    'ONE'   => array('a' => 1, 'b' => 2, 'c' => 3),
    'TWO'   => array('a' => 4, 'b' => 5, 'c' => 6),
    'THREE' => array('a' => 7, 'b' => 8, 'c' => 9)
);

$new = array(
    'TWO'   => array('a' => 5, 'b' => 5, 'c' => 6),
    'THREE' => array('a' => 7, 'b' => 8, 'c' => 9),
    'FOUR'  => array('a' => 1, 'b' => 2, 'c' => 3)
);

请注意,在$ new数组中,我删除了'ONE',添加了'FOUR',并将'TWO'=>'a'的值从4更改为5.

这是我目前的(工作)解决方案,但我觉得我不需要编写这么多代码,而且我不确定它是否会在更大的数组上变慢。

$added = array();
$removed = array();
$changed = array();

foreach ($old as $old_key => $old_value) {
    if (!in_array($old_key, array_keys($new))) {
        $removed[] = $old_value;
        unset($old[$old_key]);
    }
}

foreach ($new as $new_key => $new_value) {
    if (!in_array($new_key, array_keys($old))) {
        $added[] = $new_value;
        unset($new[$new_key]);
    }
}

$changed = array_udiff($new, $old, create_function(
    '$a,$b',
    'return strcmp(implode("", $a), implode("", $b));'
));

1 个答案:

答案 0 :(得分:5)

您可以使用array_diff_key轻松找出已添加或删除的项目:

$removed = array_diff_key($old, $new);
$added = array_diff_key($new, $old);

要找出哪些项目已更改,您可以先使用array_intersect_key缩小可能的候选项和直接数组比较,看看有哪些更改:

$possiblyChanged = array_intersect_key($old, $new);
foreach ($possiblyChanged as $key => $value) {
    if ($new[$key] !== $value) {
         $changed[$key] = $value;
    }
}