开发者

how to get keys that correspond to different values in two arrays?

$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tom开发者_如何学编程ato'=>3,'apple'=>5,'banana'=>20);

I need function that would return array('tomato','banana'), consider that it omits keys that don't exist in one or the other array. Apple has the same value in both arrays, so it should be omitted - returned should be only keys whose values differ and are set


This should work (demo):

$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$result = array_keys(array_diff(array_intersect_key($arr1, $arr2), $arr2));
print_r($result);

Output:

Array
(
    [0] => tomato
    [1] => banana
)

Reference:

  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_diff — Computes the difference of arrays
  • array_keys — Return all the keys or a subset of the keys of an array


$array3 = array();
foreach(array_intersect_key($array1, $array2) as $key => $v){
 if($array1[$key] != $array2[$key]) $array3[] = $key;
}


<?php
/**
* Returns an array which contains keys which are in both $array1
* and $array2, and which have different values.
*/
function getKeysWhichMatchAndHaveDifferentValues($array1, $array2)
{
    $arrIntersected = array_intersect_key($array1, $array2);
    foreach($arrIntersected as $key => $value) 
    {
            if($array2[$key] == $value) {
                    unset($arrIntersected[$key]);
            }
    }
    return array_keys($arrIntersected);
}

$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);

$final = getKeysWhichMatchAndHaveDifferentValues($arr1, $arr2);
echo '<pre>' . print_r($final) . '</pre>';
?>


I would do simple loop.

Of course if you will need to compare large arrays, the native PHP functions could help a lot. Still can't answer right now what would be the most optimal way to do this.


You could do this using array_intersect and array_keys.

$arr3 = array_intersect(array_keys($arr1), array_keys($arr2));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜