dougou7008
2017-08-19 11:11
浏览 189

比较两个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"]';

图片转代码服务由CSDN问答提供 功能建议

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dsgdfg30210 2017-08-19 11:26
    已采纳

    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
    )
    
    打赏 评论
  • doudizhu2222 2017-08-19 11:19

    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  
    
    打赏 评论
  • douzao2590 2017-08-19 11:25

    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);
    
    打赏 评论

相关推荐 更多相似问题