基于相同的键和值将两个数组合并为一个

时间:2013-07-13 07:56:06

标签: php json

我将以下数组合并到一个数组中时遇到了麻烦。如果提供任何指导或代码片段,那将非常有用。

我有这个数组:

[{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"}]
[{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"},{"id":"RMU-442","test":"Softening Point","key":"tests"}]

这是我想要的结果:

[{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"},{"id":"RMU-442","test":"Softening Point","key":"tests"}]

2 个答案:

答案 0 :(得分:0)

因为原始JSON数据包含对象数组,所以没有PHP函数可以执行合并。这是一个适用于简单对象的PHP编码解决方案:

<?php
function searchObjects($needle, $haystack) {
    foreach ($haystack as $value) {
     if ($value == $needle) {  //Object comparison works for simple objects
        return true;
    }
}
    return false;
}

$array1 = json_decode('[{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"}]');

$array2 = json_decode('[{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"}, 
       {"id":"RMU-442","test":"Softening Point","key":"tests"}]');

foreach ($array2 as $value){
  if (!searchObjects($value, $array1)) {
        $array1[] = $value;
  }
}

$result = json_encode($array1);
echo $result;
?>

答案 1 :(得分:-2)

包含jQuery并使用以下代码

 var v = [{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"}];
 var v1 = [{"id":"RMU-442","test":"Flash Point\/Fire Point","key":"tests"}, 
           {"id":"RMU-442","test":"Softening Point","key":"tests"}];
 var v3= jQuery.merge(v,v1);
 console.log(v3);

see jsFiddle here