-1

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

我有这个数组:

[{"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"}]
4

2 回答 2

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;
?>
于 2013-07-13T09:04:07.303 回答
-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);

在这里看到 jsFiddle

于 2013-07-13T08:06:23.617 回答