组合多个JSON数组

时间:2017-05-26 01:20:53

标签: php arrays json

我正在尝试根据匹配字段" employerPayeReference"组合以下数组。以下数组

数组1:

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

数组2:

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

我怎样才能得到一个看起来像这样的数组

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

(即)它基于雇主参考匹配进行组合。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:3)

您可以使用array_replace_recursive来获得结果。但是,因为它适用于数组,您需要使用json_decode将json转换为数组,然后使用json_encode进行编码以获得所需的结果。

$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);

单线:

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

有一种类似的方法来处理来自另一个SO answer

的数组