user1853834
user1853834

Reputation: 3

Compare two uneven json array in php

Hi I have two uneven JSON array which I am decoding in php. First array has 2 values and other has 3 values now I want to search for an 'id' number from first array to second array and display the names. Is there any way to do it? I would appreciate your help. Thank you

Here is the example of my first array

[
{
    "id": 5,
    "pb_first_name": "Respect",
    "pb_last_name": "Respect"
},
{
    "id": 41,
    "pb_first_name": "Master",
    "pb_last_name": "Master"
}

]

Here is the second JSON array

[
{
    "id": 5,
    "type": "Suite",
    "description": "",
    "number": "105",
    "floor": 1
},
{
   "id": 23,
    "type": "Suite",
    "description": "",
    "number": "220",
    "floor": 2
},
{
   "id": 41,
    "type": "Penthouse",
    "description": "",
    "number": "410",
    "floor": 4
}

]

Upvotes: 0

Views: 1892

Answers (1)

Teena Thomas
Teena Thomas

Reputation: 5239

You can use array_diff, array_intersect, in_array or array_search. Since you haven't mentioned any code, I don't know which one would best suit your need.

Manuals: array_diff, array_intersect, in_array, array_search

Edit:

$arr1 = array(...); // 1st array
$arr2 = array(...); //2nd array
foreach($arr2 as $v) {
  foreach($arr1 as $m) {
   if ($v['id'] == $m['id'])
    echo $m[pb_first_name'] . " " . $m['pb_last_name'];
 }
}

Upvotes: 2

Related Questions