简体   繁体   English

如何在PHP中找到两个数组之间的差异?

[英]How to find difference between two arrays in PHP?

Here is array 1: 这是数组1:

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

Here is array 2: 这是数组2:

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

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): 我试图找到这两个数组之间的区别,并返回以下内容(如您所见,主机名,然后是数组2中找不到的项目的相应IP地址):

Array ( [ZYX99] => 10.123.456.81)

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

This should work for you: 这应该为您工作:

(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) (这里我只是使用array_diff_key()来获取键的差。我使用array_flip()翻转了第二个数组,以便将值更改为键)

<?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);

?>

Output: 输出:

Array ( [ZYX99] => 10.123.456.81 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM