【问题标题】:Comparing JSON arrays by a specific key in PHP通过 PHP 中的特定键比较 JSON 数组
【发布时间】:2013-02-25 16:16:22
【问题描述】:

我想使用数组 A 中的数据(如下),但只有当数组 A 中的项目 ID ID 匹配时> 来自数组 B 中的 items(也位于下方)。我将如何通过 PHP 通过 ID (来自items)的键来比较这两个 JSON 数组?我想我首先需要用json_decode 转换它们,但我不知道接下来该去哪里?

请注意,数组 B 有更多的嵌套(“items”、“something”和“posts”),这与数组 A 不同。我想比较来自 items 的 ID,不是强>posts.

数组 A:

{
  "data": [{
      "category": "Games",
      "id": "45345"
    }, 
    {
      "category": "Music",
      "id": "345345345"
    }, 
    {
      "category": "Food",
      "id": "1"
    }, 
    {
      "category": "Pets",
      "id": "13245345"
    }]
}

数组 B:

{
  "data":  {
    "something": "blah",
    "posts":  [{
        "id": "34241",
        "title": "orange"
      }],
    "items":  [{
        "id": "1",
        "name": "orange"
      },
      {
        "id": "2",
        "name": "dog"
      },
      {
        "id": "3",
        "name": "cat"
      },
      {
        "id": "4",
        "name": "apple"
      }]
  }
}

对于上述情况,它将遍历数组 A 并输出数组 A 中除第三项之外的所有内容,因为该项 (1) 的 id 与数组 B items 中的一个 id 匹配。

【问题讨论】:

  • “似乎不起作用”。为什么?我觉得这个解决方案很好。
  • 然后将 foreach ($array1 as $key => $value) { 更改为 foreach ($array1["data"] as $key => $value) {。认真的吗?

标签: php json compare


【解决方案1】:

根据我的理解,您需要一个两步流程。第一个是从第一个 JSON blob 中提取 id,第二个是过滤第二个 JSON blob。所以基本上,我们有mapfilter。碰巧我们可以为此使用 PHP 的内置函数:

$ids = array_map(
    function($value) { 
        return $value['id']; 
    }, 
    $array2['data']['items']
);

首先,我们将第二个数组的 items 元素展平为单独的 id。我们在 data.items 数组上“映射”,并返回每个数组的 $id 属性。现在,我们有一个 id 数组...

$new = array_filter(
    $array1['data'],
    function($var) use ($ids) {
        return !in_array($var['id'], $ids);
    }
);

现在,我们使用它来过滤第一个 blobs 数组以确定元素是否是新元素。所以我们使用数组过滤器来为我们处理它。我们需要做的就是检查$ids 数组以查看当前数据的id 是否存在(如果存在,则将其丢弃)。所以我们希望将数组过滤为只有 not in array of $ids 的变量(因此 !in_array($var['id'], $ids)...)

【讨论】:

    【解决方案2】:

    将项目解码为 PHP 数组。使用像 array_diff() 这样的 SPL 来获取差异比较的结果。

    帮助您入门的参考资料:

    http://www.php.net/manual/en/function.array-diff.php

    http://php.net/manual/en/function.array-diff-key.php

    http://www.php.net/manual/en/function.json-decode.php

    应该是关于你在寻找什么

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2021-12-18
      • 1970-01-01
      • 2023-03-12
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多