0

I have a json like below :

{"fav":[{"id":14823},{"id":14817},{"id":14811},{"id":14775}],"scheduled":[{"id":14811},{"id":14817}]}

I want to search scheduled in fav, if it exist, it will be removed in fav

The result which I want as :

 {"fav":[{"id":14823},{"id":14775}],"scheduled":[{"id":14811},{"id":14817}]}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

1 Answers1

1

After you decode the JSON:

$data = json_decode($json, true);

You can use array_diff to remove the values in fav that are also in scheduled.

$fav = array_values(array_diff(
    array_column($data['fav'], 'id'),
    array_column($data['scheduled'], 'id')));

(The array_values is necessary because array_diff will preserve the keys, and you'll need sequential zero-indexed keys for reencoding to JSON to work properly.)

Then map those values back to the {id: value} format and reassign the result to $data['fav'].

$data['fav'] = array_map(function($item){ return ['id' => $item]; }, $fav);

Then, obviously, reencode as JSON.

$json = json_encode($data);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80