【问题标题】:Comparing 2 json strings to find new entries比较 2 个 json 字符串以查找新条目
【发布时间】:2016-05-06 04:37:49
【问题描述】:

我正在尝试将 2 个 json 字符串相互比较以查找列表中的所有新条目。

这就是我比较它们的方式:

$json = json_decode(file_get_contents("new.json"), true);
$last_json = json_decode(file_get_contents("last.json"), true);
$difference = array_diff($json, $last_json);

print_r($difference);   

我希望它返回一个包含所有新条目的数组。但是,我只是得到一个空数组作为回报。

任何帮助将不胜感激!

附加信息: 我也在尝试比较数组的值。这就是我尝试这样做的方式:

foreach($json["whitelist_name"] AS $json_key => $json_val) {
        foreach($last_json["whitelist_name"] AS $last_json_key => $last_json_val) {
            if($json["whitelist_name"] != $last_json["whitelist_name"]) {
                echo $json["whitelist_name"];
            }
        }
    }

但是,$json["whitelist_name"] 似乎是未定义的

【问题讨论】:

  • 您的 json 解码返回关联数组。所以 array_diff_assoc 可能会有所帮助。
  • 太棒了,成功了!你知道是否有可能找出是否有人更改了他们的 whitelist_name 吗?

标签: php arrays json compare


【解决方案1】:

array_diff_assoc 是获取关联数组差异的方法:

$json = json_decode(file_get_contents("new.json"), true);
$last_json = json_decode(file_get_contents("last.json"), true);
$difference = array_diff_assoc($json, $last_json);

print_r($difference); 

这段小代码会找出新json中的whitelist_name是否与旧json不同

foreach($last_json as $key=>$value){
    if($value['whitelist_name'] != $json[$key]['whitelist_name']){
        // value is changed
    }else{
        // value is not changed
    }
} 

【讨论】:

  • 太棒了,成功了!你知道是否有可能找出是否有人更改了他们的 whitelist_name 吗?
  • 要查找更改的值,您必须遍历数组并将其与另一个进行比较以了解它们是否相同。
  • @MartinO 我已经更新了找出变化值的答案
  • 很高兴知道它有帮助
猜你喜欢
  • 1970-01-01
  • 2017-10-17
  • 2023-03-19
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多