我跟着这个但是它仍然不适合我:How to remove duplicate data of JSON object using PHP
在我的PHP
文件中,我有3个JSON arrays
:
{"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"}]}
我想合并这些并删除重复项。我这样想:
//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"
。
你能告诉我如何解决这个问题或其他方法吗?
答案 0 :(得分:1)
使用以下解决方案
$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));