Search code examples
phparray-mergearray-unique

Trying to remove duplicates from JSON array with array_unique and array_values


I was following this but it still doesn't work for me: How to remove duplicate data of JSON object using PHP

In my PHP file I have 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"}]}

I want to merge these and remove duplicates. I'm trying like this:

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

But I am getting:

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"}]]

As you can see, duplicates are not removed, and there's extra [] and "results" is missing.

Can you tell me how I can fix this, or another way to do it?


Solution

  • Use below solution

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