比较PHP中具有相同键的2个JSON数组
具有相同密钥的2个不同JSON数组,如下所示: 阵列1:比较PHP中具有相同键的2个JSON数组,php,arrays,json,Php,Arrays,Json,具有相同密钥的2个不同JSON数组,如下所示: 阵列1: { "fruit1" : "Apple", "fruit2" : "Banana", "fruit3" : "Grapes" } 阵列2: { "fruit1" : "First Fruit", "fruit2" : "Second Fruit", "fruit3" : "Third Fruit" } 如您所见,两个数组具有相同的键但值不同,现在我想要的是结果或显示如下: First Fruit is Apple Second Fru
{ "fruit1" : "Apple", "fruit2" : "Banana", "fruit3" : "Grapes" }
阵列2:
{ "fruit1" : "First Fruit", "fruit2" : "Second Fruit", "fruit3" : "Third Fruit" }
如您所见,两个数组具有相同的键但值不同,现在我想要的是结果或显示如下:
First Fruit is Apple
Second Fruit is Banana
Third Fruit is Grapes
谢谢 想法是将JSON字符串(没有JSON数组)转换为关联数组,然后遍历键/值对。想法是将JSON字符串(没有JSON数组)转换为关联数组,然后遍历键/值对。
$str1 = '{ "fruit1" : "Apple", "fruit2" : "Banana", "fruit3" : "Grapes" }';
$str2 = '{ "fruit1" : "First Fruit", "fruit2" : "Second Fruit", "fruit3" : "Third Fruit" }';
$array1 = json_decode($str1);
$array2 = json_decode($str2);
foreach ($array1 as $key => $value) {
if (isset($array2[$key]) {
echo $value . " is " . $array2[$key];
} else {
echo $value . " has no match in array2.";
}
}
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
foreach($array1 as $key => $val) {
if (isset($array2[$key])) {
echo $array1[$key],' is ',$array2[$key];
echo PHP_EOL;
}
}