【问题标题】:Most efficient way to join multiple json file in PHP在 PHP 中加入多个 json 文件的最有效方法
【发布时间】:2020-06-25 11:03:43
【问题描述】:

我正在寻找一种有效的解决方案,将多个 json 数组合并为一个,并删除重复项。 我有多个具有这种结构的 json 文件:

[
    {
        "@_fa": "true",
        "link": [],
        "prism:url": "",
        "dc:identifier": "ID-X",
        "eid": "ID-X",
        "dc:title": "",
        "dc:creator": "",
        "prism:publicationName": "",
        "prism:issn": "",
        "prism:eIssn": "",
        "prism:volume": "",
        "prism:issueIdentifier": "",
        "prism:pageRange": "",
        "prism:coverDate": "2020-05-01",
        "prism:coverDisplayDate": "",
        "prism:doi": "",
        "dc:description": "",
        "citedby-count": "0",
        "affiliation": [],
        "prism:aggregationType": "Jounal",
        "subtype": "ar",
        "subtypeDescription": "",
        "author-count": {
            "@limit": "100",
            "@total": "5",
            "$": "5"
        },
        "author": [],
        "article-number": "",
        "source-id": "",
        "fund-no": "",
        "fund-sponsor": "",
        "openaccess": "0",
        "openaccessFlag": false
    },
   {
       ...
   }
]

我是这样读取这些文件的:

$json_1 = json_decode(file_get_contents('file_1.json'));
$json_2 = json_decode(file_get_contents('file_2.json'));
$json_3 = json_decode(file_get_contents('file_3.json'));

这些数组可以包含相同的元素,这些元素可以通过一些唯一字段来识别,例如 dc:identifiereiddc:title,它们都是唯一的。

我想将所有 $json_ 变量合并为一个,只保留一次不同数组之间的公共元素。什么是最好和最有效的解决方案?

【问题讨论】:

    标签: php json


    【解决方案1】:

    如果我正确理解您的问题,array_merge(array1,array2,....,arrayN) 应该可以工作。

    $json_1 = json_decode(file_get_contents('file_1.json'));
    $json_2 = json_decode(file_get_contents('file_2.json'));
    $json_3 = json_decode(file_get_contents('file_3.json'));
    $result = array_merge($json_1,$json_2,$json_3);
    

    【讨论】:

    • 但是 array_merge 保留双元素?
    • 之后您可以使用 array_unique() php.net/manual/en/function.array-unique.php 删除重复项。
    • 我已经尝试过你的解决方案,但双元素仍然存在
    • 如何将json存储在一个数组中,然后首先复制到结果(result=json[0].slice()),然后是for(i=1;i<jsons.length;i++)和双for循环(j,k)比较结果的元素和元素jsons[i] 如果找到匹配则中断,或者如果循环结束但未找到则推送,然后是下一个 json... 注意:要比较,我建议使用 JSON.stringify(result[j])==JSON.stringify(jsons[i][k])
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 2018-08-10
    • 1970-01-01
    • 2021-10-13
    • 2016-11-01
    • 2016-03-04
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多