尝试使用 array_unique 和 array_values 从 JSON 数组中删除重复项



我一直在关注这个,但它仍然对我不起作用: 如何使用PHP删除JSON对象的重复数据

在我的PHP文件中,我有 3 个JSON arrays

{"results":[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},
{"cat_id":4,"cat_name":"dentist"}]}

数组 2:

{"results":[{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"}]}

数组 3:

{"results":[{"cat_id":4,"cat_name":"dentist"},{"cat_id":5,"cat_name":"stocktaker"},
{"cat_id":3,"cat_name":"electrician"}]}

我想合并这些并删除重复项。我正在尝试这样做:

//this works good, all merged into one
$array1AndArray2AndArray3 = array_merge_recursive($array1,$array2, $array3);
//now I want to remove duplicates:
$uniqueArray = array_values(array_unique($array1AndArray2AndArray3, SORT_REGULAR));
echo "Unique array is " . json_encode($uniqueArray);

但我得到:

Unique array is [[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},
{"cat_id":4,"cat_name":"dentist"},
{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"},
{"cat_id":4,"cat_name":"dentist"},
{"cat_id":5,"cat_name":"stocktaker"},
{"cat_id":3,"cat_name":"electrician"}]]

如您所见,重复项不会被删除,并且有额外的[]并且缺少"results"

你能告诉我如何解决这个问题,或者另一种方法吗?

使用以下解决方案

$array1 = '{"results":[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},{"cat_id":4,"cat_name":"dentist"}]}';
$array2 = '{"results":[{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},{"cat_id":"9","cat_name":"builder"}]}';
$array3 = '{"results":[{"cat_id":4,"cat_name":"dentist"},{"cat_id":5,"cat_name":"stocktaker"},{"cat_id":3,"cat_name":"electrician"}]}';
$array1 =  json_decode($array1, TRUE);
$array2 =  json_decode($array2, TRUE);
$array3 =  json_decode($array3, TRUE);
$array4 = array_merge_recursive($array1['results'], $array2['results'], $array3['results']);
$uniqueArray['results'] = array_values(array_unique($array4, SORT_REGULAR));

相关内容

  • 没有找到相关文章

最新更新