【问题标题】:PHP Multi Array Merging JSONPHP多数组合并JSON
【发布时间】:2021-07-21 19:58:59
【问题描述】:

我得到了这样的 JSON 输出

{ [objects{}] [to] [from] [total] }

由于我要从中提取的 API,我一次只能提取 500 条记录,我想做的是将多个 json 输出的对象部分合并到一个更大的记录集中。

我已尝试将 array_merge 与 json_encodejson_decode 一起使用,但它不起作用,我假设这是因为其他数组(to/from/total)影响了我的合并能力。

知道我该怎么做,我在考虑逐行合并,但问题是不同类型的数组有不同的元素(我只是试图合并具有相同元素的数组)。

编辑:嗯,即使使用代码标签,json 格式也不能很好地完成

{
  "objects" : [ {
    "uid" : "f7534a54-fd17-4bc2-9a26-8a567082cc86",
    "name" : "host_10.1.1.1",
    "type" : "host",
    "domain" : {
      "uid" : "8fe7e918-8530-4a7d-851c-bf8a7c3889c9",
      "name" : "Lab-Ext_VPN",
      "domain-type" : "domain"
    },
    "ipv4-address" : "10.1.1.1"
  }, {
    "uid" : "1ba63e41-4d2c-48ea-a970-66a806089ff5",
    "name" : "host_10.1.1.10",
    "type" : "host",
    "domain" : {
      "uid" : "8fe7e918-8530-4a7d-851c-bf8a7c3889c9",
      "name" : "Lab-Ext_VPN",
      "domain-type" : "domain"
    },
    "ipv4-address" : "10.1.1.10"
  }, {
    "uid" : "d798b126-25de-4138-b25d-b1edfe83d259",
    "name" : "host_10.1.1.100",
    "type" : "host",
    "domain" : {
      "uid" : "8fe7e918-8530-4a7d-851c-bf8a7c3889c9",
      "name" : "Lab-Ext_VPN",
      "domain-type" : "domain"
    },
    "ipv4-address" : "10.1.1.100"
  }, {
    "uid" : "247e1b2e-a45d-457e-87f7-78a6acdeea9f",
    "name" : "host_10.1.1.101",
    "type" : "host",
    "domain" : {
      "uid" : "8fe7e918-8530-4a7d-851c-bf8a7c3889c9",
      "name" : "Lab-Ext_VPN",
      "domain-type" : "domain"
    },
    "ipv4-address" : "10.1.1.101"
  }, {
    "uid" : "381e59a0-2094-422a-b538-8f607ec58384",
    "name" : "host_10.1.1.102",
    "type" : "host",
    "domain" : {
      "uid" : "8fe7e918-8530-4a7d-851c-bf8a7c3889c9",
      "name" : "Lab-Ext_VPN",
      "domain-type" : "domain"
    },
    "ipv4-address" : "10.1.1.102"
  } ],
  "from" : 1,
  "to" : 5,
  "total" : 614
`

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    在给定的 json 中有 4 个元素,object to fromtotal

    我假设,你必须从两个 JSON 中合并 object,得到 from 的最小值,从 to 得到最大值和 total 的总和

    function my_merge($json_1,$json_2){
        $array_1 = json_decode($json_1,true);
        $array_2 = json_decode($json_2,true);
        return ['objects'=>array_merge($array_1['objects'],$array_2['objects']),'from'=>min($array_1['from'],$array_2['from']),'to'=>max($array_1['to'],$array_2['to']),'total'=>($array_1['total']+$array_2['total'])];
    }
    

    上面,首先,json_decode 和第二个参数true 用于解码并将 JSON 转换为数组。

    其次,合并$array_1$array_2的索引[0],因为它包含对象。对min maxtotal 求和并返回结果数组。

    【讨论】:

    • 还是不想合并数组,其实我只关心对象数组,我已经在原帖中放了一个json输出的样本。
    猜你喜欢
    • 2020-02-29
    • 2017-02-24
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多