Zach Reed
Zach Reed

Reputation: 683

Comparing JSON arrays by a specific key in PHP

I want to use the data from array A (below), but only when the item ID from array A does NOT match an ID from items in array B (also, below). How would I go about comparing these two JSON array's by the key of ID (from items) via PHP? I imagine I first need to convert them with json_decode, but I'm not sure where to go after that?

Please note that array B has more nests ("items", "something", & "posts"), unlike array A. I want to compare the ID from items, not posts.

Array A:

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

Array 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"
      }]
  }
}

With the case above, it would run through array A and output everything from array A except for the third item, since the id of that item (1) matches one of the id's in array B items.

Upvotes: 0

Views: 1830

Answers (2)

ircmaxell
ircmaxell

Reputation: 165261

Based on my understanding, you need a two step process. The first is extracting the ids from the first JSON blob, and the second is filtering the second JSON blob. So basically, we have map and filter. And it just so happens we can use PHP's inbuilt functions for this:

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

First, we flatten the second array's items element into the individual ids. We "map" over the data.items array, and return the $id attribute of each array. Now, we have an array of ids...

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

Now, we use that to filter the first blobs array to determine if an element is new or not. So we use array filter to handle it for us. All we need to do is check the $ids array to see if the current data's id is there (and if it is, throw it away). So we want to filter the array to be only variables that are not in array of $ids (hence !in_array($var['id'], $ids)...)

Upvotes: 2

David J Eddy
David J Eddy

Reputation: 2037

Decode the items into PHP arrays. Use a SPL like array_diff() to get the results of a diff comparison.

Referances to get you started:

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

Should be about what your looking for

Upvotes: 2

Related Questions