使用 array_diff 比较两个数组 [英] Comparing two arrays with array_diff
本文介绍了使用 array_diff 比较两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,我正在尝试将两个数组与 array_diff 进行比较,但是我一直没有得到任何结果.我不确定这是否重要,但数组中有很多字段,我真的只想比较 1 个字段......这可能吗?我错过了什么?
I have the following code and am trying to compare two array's with array_diff however I keep getting no results. I not sure if it matters, but there are many fields in the array and I really only want to compare 1 field...is this possible? what am I missing?
<?php
$json = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&fmt=json");
$json2 = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&fmt=json");
$array1 = json_decode($json, TRUE);
$array2 = json_decode($json2, TRUE);
if ( $array1 == $array2 ) {
echo 'There are no differences';
}else
var_dump(array_diff($array2, $array1));
echo 'they are different';
?>
推荐答案
您将需要相互检查数组:
You will need to check the arrays against each other:
$Array_1 = array (1,2,3,4,5);
$Array_2 = array(1,2,3,4,5,6);
print_r(array_diff($Array_1,$Array_2));
将输出:
Array
(
)
鉴于:
print_r(array_diff($Array_2,$Array_1));
将输出:
Array
(
[5] => 6
)
所以这可能是一个解决方案:
So this might be a solution:
function ArrayDiff ($Array_1, $Array_2){
$Compare_1_To_2 = array_diff($Array_1,$Array_2);
$Compare_2_To_1 = array_diff($Array_2,$Array_1);
$Difference_Array = array_merge($Compare_1_To_2,$Compare_2_To_1);
return $Difference_Array;
}
print_r(ArrayDiff($Array_1,$Array_2));
输出:
Array
(
[0] => 6
)
<小时>
将其放入 if 语句中:
Putting this into an if statement:
$Differences = ArrayDiff($Array_2,$Array_1);
if (count($Differences) > 0){
echo 'There Are Differences Between The Array:';
foreach ($Differences AS $Different){
echo "<br>".$Different;
}
所有示例和代码都基于开始时的数组($Array_1 和 $Array_2)
All the examples and code is based off the arrays at the start ($Array_1 and $Array_2)
这篇关于使用 array_diff 比较两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文