0

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

2
  • What did you try, and why did it not work? Commented May 26, 2017 at 1:22
  • I am repeating this loop on each array, but it relies on the payeref being in the same order in each array which is not always the case. foreach($input as $parent) { foreach($parent as $values) { echo "<BR>"; echo $values[employerPayeReference]; echo $values[employerName]; } } Commented May 26, 2017 at 1:26

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you do much! Exactly what i was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.