首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何识别两个jsons之间的不同数组

如何识别两个jsons之间的不同数组
EN

Stack Overflow用户
提问于 2018-05-10 03:54:10
回答 2查看 36关注 0票数 1

在比较两个数组时,我找到了不同的答案,但在我的例子中没有一个起作用。我有两个Jsons,一个保存旧值的Old.json和要保存新值的New.json。我只想把New.json中还没有的新东西保存在Old.json中

OLD.JSON

代码语言:javascript
复制
{
    "jogos-da-copa": [
        "/videos/291856.html",
        "/videos/291830.html",
        "/videos/291792.html",
        "/videos/291759.html",
        "/videos/291720.html",
        "/videos/291705.html"
    ],
    "apresentacao": [
        "/videos/2926328.html",
        "/videos/67.html",
        "/videos/36.html",
        "/videos/3.html"
    ]
}

NEW.JSON

代码语言:javascript
复制
{
    "jogos-da-copa": [
        "/videos/291887.html",
        "/videos/291856.html",
        "/videos/291830.html",
        "/videos/291792.html",
        "/videos/291759.html",
        "/videos/291720.html",
        "/videos/291705.html"
    ],
    "apresentacao": [
        "/videos/2926385.html",
        "/videos/2926328.html",
        "/videos/67.html",
        "/videos/36.html",
        "/videos/3.html"
    ]
}

我使用了这段代码,但它没有显示这些差异。

代码语言:javascript
复制
$old1 = json_decode(file_get_contents('old.json'), true);
$new2 = json_decode(file_get_contents('new.json'), true);
$test = [];

foreach ($old1 as $key1 => $olds1) {

    foreach ($new2 as $key2 => $news2 ) {

    $test[] = array_diff($olds1, $news2);

    }

}

var_dump($test);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-10 04:49:22

请使用下面的函数并将旧的和新的数组传递给参数

代码语言:javascript
复制
$old = json_decode($old_json, true);
$new = json_decode($new_json, true);

$array_keys = array_keys( array_merge( $old, $new));

$dif_array = array();
foreach($array_keys as $key)
{
    if(array_key_exists($key, $old) && array_diff($new[$key], $old[$key])){
        $dif_array[$key] = array_diff($new[$key], $old[$key]);
    } else {
        $dif_array[$key] = $new[$key];
    }
}

$final_array = array_merge_recursive($old, $dif_array);
票数 1
EN

Stack Overflow用户

发布于 2018-05-10 04:13:57

来自比较文档:

将array1与一个或多个其他数组进行比较,并返回任何其他数组中不存在的array1中的值。

在您的示例中,新数组包含来自旧数组的所有值。要获得所有新值的列表,您需要将参数转换为:

代码语言:javascript
复制
$old1 = json_decode(file_get_contents('old.json'), true);
$new2 = json_decode(file_get_contents('new.json'), true);
$test = [];

foreach ($old1 as $key1 => $olds1) {

    foreach ($new2 as $key2 => $news2 ) {
        $test[] = array_diff($news2, $olds1);
    }

}

var_dump($test);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50265222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档