1

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"]';
5
  • post the expected result Commented Aug 19, 2017 at 11:14
  • just remove duplicate and show original data. Commented Aug 19, 2017 at 11:18
  • post that original data Commented Aug 19, 2017 at 11:22
  • "10.00 am To 11.00 am" Commented Aug 19, 2017 at 11:22
  • 1
    Possible duplicate of difference between two arrays ...specifically see the selected answer: exact duplicate of this question. Commented Aug 19, 2017 at 12:16

3 Answers 3

1

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

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  

2 Comments

but your's Array ( [0] => 7.00 am To 8.00 am [1] => 1.00 pm To 2.00 pm [2] => 2.00 pm To 3.00 pm [6] => 10.00 am To 11.00 am ) like that
oh got it so you want to remove duplicate data too ..sorry mate ...i missed that
1

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

2 Comments

$out = array_values($json2); $arry_merge = (array_merge($json1,$json2)); echo json_encode($arry_merge).'--op';
finally i got @Mr Alb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.