2

我使用这段代码:

 $new = array(
     "123" => "a",
     "456" => "b"
 );

 $old = array(
     "123" => "a",
     "456" => "b"
 );

然后$new数组变成这样:

 $new = array(
     "456" => "b",
     "123" => "c",
     "789" => "e"
 );

如您所见,$new数组的数量增加了,元素的顺序发生了变化,键的值123也发生了变化。我需要将$new数组与$old数组进行比较,并且只捕获对键值所做的更改,123而不关心元素的顺序和数量。我试过:

 $result = array_diff( $new, $old );
 print_r( $result );

输出 :

 Array ( [123] => c [789] => e )
4

3 回答 3

5

更新。相当混乱。现在我想我们明白了

$old = array(
    "123"    => "a",
    "456"    => "b"
);
$new = array(
    "456"    => "b",
    "123"    => "c", // catch this (element in old array that is changed)
    "789"    => "e"
);

$new2 = array();
foreach ($new as $key => $new_val)
{
    if (isset($old[$key])) // belongs to old array?
    {
        if ($old[$key] != $new_val) // has changed?
            $new2[$key] = $new[$key]; // catch it
    }
}

// output $new2:
array (
  123 => 'c',
)
于 2012-12-31T12:41:19.407 回答
2

您首先希望将这些元素与(参见 参考资料)$new进行更改:$oldarray_diff_assoc

$changed = array_diff_assoc($new, $old);

在该结果中,您只想拥有那些具有其键的元素$old(请参阅 参考资料array_intersect_key):

$result  = array_intersect_key($changed, $old);

就是这样。如果有帮助,您可以将它们相互包装:

array_intersect_key(array_diff_assoc($new, $old), $old);

结果是:

array(1) {
  [123] =>
  string(1) "c"
}

完整示例(演示):

$old = array(
    "123" => "a",
    "456" => "b"
);

$new = array(
    "456" => "b",
    "123" => "c", // catch only the change made on the value at key 123 
    "789" => "e"
);

$changed = array_diff_assoc($new, $old);
$result  = array_intersect_key($changed, $old);

var_dump($result);

最后一点:PHP 中有许多数组函数。值得仔细阅读列表并查看合适的内容,因为大多数情况下您只需要其中一两个即可完成此类工作。

于 2012-12-31T15:14:39.953 回答
0

您将此代码用于您的要求

 <?php
    function key_compare_func($key1, $key2)
    {
        if ($key1 == $key2)
            return 0;
        else if ($key1 > $key2)
            return 1;
        else
            return -1;
    }

    $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
    $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

    var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
    ?>
于 2012-12-31T12:39:36.403 回答