Reputation: 59
So i get info from a JSON file and i get one array called "items" and pass it to this array in PHP:
"items": [
{
"id": "2",
"parent": null,
"itemType": 0,
"title": "Manuel Perez",
"description": "Chief Executive Officer (CEO)",
"phone": "(491) 183-55-45",
"email": "[email protected]",
"photo": "",
"image": "demo/images/photos/m.png",
"href": "showdetails.php?recordid=2",
"isVisible": true
}
Then i have to compare this with another that can contain more or less items, but i can take those elements that change the size of the array. But when i want to get the difference when the size is the same and a value of a key is different when i cant make it work.
If in the second array in the position 2 the value of "itemType" change to 1 i want to get somenthing like this:
Array[2] - > "itemType": 1
And so that way i can know if something changed.
Upvotes: 1
Views: 66
Reputation: 392
Suppose you have two arrays $items1 and $items2:
$items1 = [
"id" => "2",
"itemType" => 0,
];
$items2 = [
"parent" => null,
"itemType" => 1,
];
To get the things that are added or modified in $items2 compared to $item1, you can use:
array_diff_assoc($items2, $items1) // displays ['parent' => null, 'itemType' => 1]
To get the things that are added or modified in $items1 compared to $item2, you can use:
array_diff_assoc($items1, $items2) // displays ['id' => "2", 'itemType' => 0]
If you want both, you can combine these two arrays and use them as you wish.
Upvotes: 1
Reputation: 11
First of all covert your JSON data into Array and take items form both into $jsonArray1 and $jsonArray2 respectively.
Now sort your both array by key like this ksort($jsonArray1); ksort($jsonArray2);
Now take difference of both array $diffData = array_diff_assoc($jsonArray1, $jsonArray2);
Output: $diffData is your output, hope this will help!!
Upvotes: 0