比较两个json数组并删除PHP中的重复项

问题描述:

here i want compare two json array and remove duplicates.

 $jsonArray1 = '["7.00 am To 8.00 am","1.00 pm To 2.00 pm","2.00 pm To 3.00 pm"]';
    $jsonArray2 = '["7.00 am To 8.00 am","1.00 pm To 2.00 pm","2.00 pm To 3.00 pm","10.00 am To 11.00 am"]';

这里我想比较两个json数组并删除重复项。 h3>
  $ jsonArray1 ='[“早上7点到早上8点”,“下午1点到下午2点”,“下午2点到下午3点”]'; 
 $ jsonArray2 ='[“早上7点到早上8点”,“下午1点00分 到下午2点“,”下午2点到下午3点“,”上午10点到上午11点“]'; 
  code>  pre> 
  div>

The solution using array_intersect and array_filter functions:

$json_str1 = '["7.00 am To 8.00 am","1.00 pm To 2.00 pm","2.00 pm To 3.00 pm"]';
$json_str2 = '["7.00 am To 8.00 am","1.00 pm To 2.00 pm","2.00 pm To 3.00 pm","10.00 am To 11.00 am"]';

list($arr1, $arr2) = [json_decode($json_str1), json_decode($json_str2)];
$common_items = array_intersect($arr2, $arr1);
$result = array_filter(array_merge($arr1, $arr2), function($v) use($common_items){
    return !in_array($v, $common_items);
});

print_r($result);

The output:

Array
(
    [6] => 10.00 am To 11.00 am
)

First convert json string to array using json_decode and USE array_diff to find different value

Here's the code -

   $arr1 = json_decode($jsonArray1); 
   $arr2 = json_decode($jsonArray2); 

   $newarr = array_diff($arr2, $arr1);
   print_r($newarr);  // php array format
   json_encode($newarr); // json format  

Try this:

//you have to decode arrays
$json1 = json_decode( $jsonArray1, true);
$json2 = json_decode( $jsonArray2, true);

//find duplicates
$find_duplicates = array_intersect($json1, $json2);

//remove duplicates from first array 
$json1 = array_diff($json1, $find_duplicates);

///remove duplicates from second array 
$json2 = array_diff($json2, $find_duplicates);