【问题标题】:Trying to remove duplicates from JSON array with array_unique and array_values尝试使用 array_unique 和 array_values 从 JSON 数组中删除重复项
【发布时间】:2018-05-29 23:16:06
【问题描述】:

我一直在关注这个,但它仍然对我不起作用:How to remove duplicate data of JSON object using PHP

在我的 PHP 文件中,我有 3 个 JSON arrays

{"results":[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},
{"cat_id":4,"cat_name":"dentist"}]}

数组2:

 {"results":[{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"}]}

数组3:

{"results":[{"cat_id":4,"cat_name":"dentist"},{"cat_id":5,"cat_name":"stocktaker"},
{"cat_id":3,"cat_name":"electrician"}]}

我想合并这些并删除重复项。我正在尝试这样:

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

但我得到了:

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"}]]

如您所见,没有删除重复项,并且缺少额外的 []"results"

你能告诉我如何解决这个问题,或者其他方法吗?

【问题讨论】:

    标签: php array-merge array-unique


    【解决方案1】:

    使用以下解决方案

    $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,可能会在您的帖子中添加 JSON 数组已转换为显示和/或存储为 PHP 数组开始
    • @TCooper - 我已经用它更新了你的代码,但你可能会被删除那个答案:)
    • 是的,不想用无用的信息弄乱页面(我的回答)。很抱歉劫持了你的答案 Jaydp - 我最近也做了类似的回答
    • 好东西,谢谢 - 刚刚做了一个小编辑以获得“结果”部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多