MK_03 MK_03 - 1 month ago 4
PHP Question

Get elements with same key but different value in two PHP arrays

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": "ste.ballmer@name.com",
"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.

Answer

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($tab2, $tab1) // 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($tab1, $tab2) // displays ['id' => "2", 'itemType' => 0]

If you want both, you can combine these two arrays and use them as you wish.

Comments