在php中比较两个数组

时间:2012-12-31 12:21:34

标签: php arrays

我使用此代码:

 $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 )

3 个答案:

答案 0 :(得分: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',
)

答案 1 :(得分:2)

首先,您希望将$new的元素与$old相比发生更改(请参阅array_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"
}

完整示例(Demo):

$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中有许多数组函数。值得仔细查看清单,看看哪些是合适的,因为大多数情况下你只需要其中一两个就可以完成这些工作。

答案 2 :(得分: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'));
    ?>