如何找到 PHP 中两个数组之间的差异?
How to find difference between two arrays in 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
)
我试图找出这两个数组和 return 以下内容之间的区别(如您所见,主机名,然后是数组 2 中未找到的项目的相应 IP 地址):
Array ( [ZYX99] => 10.123.456.81)
我一直在查看不同的 PHP 数组函数,但它们的数量让我不知所措:http://www.w3schools.com/php/php_ref_array.asp
这应该适合你:
(这里我只是用了array_diff_key()
to get the difference of the keys. The second array I flipped with 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);
?>
输出:
Array ( [ZYX99] => 10.123.456.81 )
这是数组 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
)
我试图找出这两个数组和 return 以下内容之间的区别(如您所见,主机名,然后是数组 2 中未找到的项目的相应 IP 地址):
Array ( [ZYX99] => 10.123.456.81)
我一直在查看不同的 PHP 数组函数,但它们的数量让我不知所措:http://www.w3schools.com/php/php_ref_array.asp
这应该适合你:
(这里我只是用了array_diff_key()
to get the difference of the keys. The second array I flipped with 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);
?>
输出:
Array ( [ZYX99] => 10.123.456.81 )