0

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?

CHarris
  • 2,693
  • 8
  • 45
  • 71

1 Answers1

1

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));
CHarris
  • 2,693
  • 8
  • 45
  • 71
Jaydp
  • 1,029
  • 9
  • 17
  • Hehe looks familiar, @CHarris, maybe add into your post that the JSON arrays are converted for display and/or are stored as PHP arrays to begin with – TCooper May 29 '18 at 23:31
  • @TCooper - I had updated your code with that but you may be removed that answer :) – Jaydp May 29 '18 at 23:33
  • yeah, didn't want to clutter the page with useless info (my answer). Sorry to hijack your answer Jaydp - I recently answered similarly – TCooper May 29 '18 at 23:34
  • Good stuff, thanks - just made a small edit to get the 'results' part. – CHarris May 29 '18 at 23:49