user3163357
user3163357

Reputation: 129

Combining multiple JSON arrays

I am trying to combine the following arrays based on a matching field "employerPayeReference" of the below arrays

Array 1:

{
    "employments": [
    {
       "employerPayeReference": "123/AB456",
       "payFromEmployment": 100.00
    },
    {
       "employerPayeReference": "456/AB456",
       "payFromEmployment": 100.00
    }
]
}

Array 2:

{
  "employments": [
    {
      "employerPayeReference": "123/AB456",
      "taxTakenOffPay": 10.00
    },
    {
      "employerPayeReference": "456/AB456",
      "taxTakenOffPay": 15.00
    }
  ]
}

How can I arrive at an array that looks like this

{
  "employments": [
    {
      "employerPayeReference": "123/AB456",
      "payFromEmployment": 100.00
      "taxTakenOffPay": 10.00
    },
    {
      "employerPayeReference": "456/AB456",
      "payFromEmployment": 100.00
      "taxTakenOffPay": 15.00
    }
  ]
}

(i.e) it is combined based on the employerPayeReference matching. Any help appreciated

Upvotes: 0

Views: 42

Answers (1)

Thamilhan
Thamilhan

Reputation: 13313

You can use array_replace_recursive to achieve the result. But since, it work with arrays, you need to convert your json to array using json_decode and then encode using json_encode to achieve desired result.

$arr1 = '{
    "employments": [
    {
       "employerPayeReference": "123/AB456",
       "payFromEmployment": 100.00
    },
    {
       "employerPayeReference": "456/AB456",
       "payFromEmployment": 100.00
    }
]
}';

$arr2 = '{
  "employments": [
    {
      "employerPayeReference": "123/AB456",
      "taxTakenOffPay": 10.00
    },
    {
      "employerPayeReference": "456/AB456",
      "taxTakenOffPay": 15.00
    }
  ]
}';

$arr1 = json_decode($arr1, true);
$arr2 = json_decode($arr2, true);

$finalArr = array_replace_recursive($arr1, $arr2);

echo json_encode($finalArr);

One liner:

echo json_encode(array_replace_recursive(json_decode($arr1, true), json_decode($arr2, true)));

There is a similar approach dealing with arrays from another SO answer

Upvotes: 2

Related Questions