【问题标题】:Compare 2 JSON Arrays with the same keys in PHP在 PHP 中比较 2 个具有相同键的 JSON 数组
【发布时间】:2012-06-27 23:49:35
【问题描述】:

2 个具有相同键的不同 JSON 数组,如下所示:

数组 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

谢谢!

【问题讨论】:

    标签: php arrays json


    【解决方案1】:
    $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.";
        }
    }
    

    【讨论】:

    • 这个想法是将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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多