如何在PHP中找到两个数组之间的差异? [英] How to find difference between two arrays in PHP?

查看:122
本文介绍了如何在PHP中找到两个数组之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是数组1:

Array ( [ABC01] => 10.123.456.78
        [ABC02] => 10.123.456.79
        [ABC03] => 10.123.456.80
        [ZYX99] => 10.123.456.81
      )

这是数组2:

Array ( [0] => ABC01
        [1] => ABC02
        [2] => ABC03
      )

我正在尝试查找这两个数组之间的区别,并返回以下内容(如您所见,主机名,然后返回数组2中未找到的项的相应IP地址):

I'm trying to find the difference between these two arrays and return the following (as you can see, the host name and then the corresponding ip address of an item not found in array 2):

Array ( [ZYX99] => 10.123.456.81)

我一直在研究不同的PHP数组函数,但对它们的数量感到不知所措: http://www.w3schools.com/php/php_ref_array.asp

I've been looking through the different PHP array functions and am overwhelmed by the amount of them: http://www.w3schools.com/php/php_ref_array.asp

推荐答案

这应该对您有用:

(这里我只是使用 array_diff_key() 来获取键的区别我用 array_flip() 翻转的第二个数组,以便将值更改为key)

(Here I just used array_diff_key() to get the difference of the keys. The second array I flipped with array_flip() so to change the values to keys)

<?php

    $arr1 = array(
            "ABC01" => "10.123.456.78",
            "ABC02" => "10.123.456.79",
            "ABC03" => "10.123.456.80",
            "ZYX99" => "10.123.456.81"
    );

    $arr2 = array("ABC01", "ABC02", "ABC03");

    $result = array_diff_key ($arr1, array_flip($arr2));
    print_r($result);

?>

输出:

Array ( [ZYX99] => 10.123.456.81 )

这篇关于如何在PHP中找到两个数组之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆