2012-06-27 103 views
1

2相同的密鑰不同JSON陣列下面:比較2個JSON陣列與PHP相同的密鑰等

陣列1:

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

陣列2:

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

,你可以請參閱2個具有相同鍵但不同值的陣列,現在我想要的是我想要的結果或顯示如下所示:

First Fruit is Apple 
Second Fruit is Banana 
Third Fruit is Grapes 

謝謝!

回答

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

的想法是將JSON字符串* *(有一個JSON數組沒有這樣的事情),以關聯數組,然後通過該鍵/值對轉換。 –

2
$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; 
    } 
}