Thursday, 30 August 2018

Compare 2 JSON Arrays with the same keys in PHP


2 different JSON arrays with same keys like below:


Array 1:
{ "fruit1" : "Apple", "fruit2" : "Banana", "fruit3" : "Grapes" }

Array 2:
{ "fruit1" : "First Fruit", "fruit2" : "Second Fruit", "fruit3" : "Third Fruit" }

As you can see, 2 arrays that have same keys but different values, now what i wanted is that i wanted the result or the display to be like this:
First Fruit is Apple
Second Fruit is Banana
Third Fruit is Grapes

Thanks!

$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.";
    }
}

0 comments:

Post a Comment