如何使用PHP删除JSON对象的重复数据 [英] How to remove duplicate data of JSON object using PHP

查看:110
本文介绍了如何使用PHP删除JSON对象的重复数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个帮助.我有一些JSON类型的数据,我想使用PHP删除重复的数据集.我在下面解释我的代码.

I need one help.I have some JSON type data and i want to remove the duplicate set of data using PHP.I am explaining my code below.

data=[
   {'member_name':member1,'no_of_users':20},
    {'member_name':member1,'no_of_users':20},
    {'member_name':member1,'no_of_users':20},
    {'member_name':member2,'no_of_users':10},
   {'member_name':member2,'no_of_users':10},
   {'member_name':member3,'no_of_users':30},
]

我的php辅助代码如下.

my php side code is given below.

$res[]=array('member_name'=>$member,'no_of_members'=>$rowno['cnt']);
$result=var_dump( array_unique( $res, SORT_REGULAR ) );
//$result = json_decode($array, TRUE );
print json_encode($result);

在这里我们可以看到许多重复数据.我只需要使用PHP从此JSON对象中删除重复数据.

Here we can see many duplicate data available.I need to remove only the duplicate data from this JSON object using PHP.Please help me.

推荐答案

首先json_decode JSON字符串,因此我们可以在PHP中使用它.然后,您应该将array_unique与标志SORT_REGULAR一起使用,以删除所有重复项,最后,再次将json_encode删除为JSON字符串.这是一个工作示例:

First json_decode the JSON string, so we can work with it in PHP. Then you should use array_unique with the flag SORT_REGULAR to remove all duplicates and lastly json_encodeit again to a JSON string. Here's a working example:

$data = '[
   {"member_name":"member1","no_of_users":20},
    {"member_name":"member1","no_of_users":20},
    {"member_name":"member1","no_of_users":20},
    {"member_name":"member2","no_of_users":10},
   {"member_name":"member2","no_of_users":10},
   {"member_name":"member3","no_of_users":30}
]';

// Make a PHP array from the JSON string.
$array = json_decode( $data, TRUE );

// Only keep unique values, by using array_unique with SORT_REGULAR as flag.
// We're using array_values here, to only retrieve the values and not the keys.
// This way json_encode will give us a nicely formatted JSON string later on.
$array = array_values( array_unique( $array, SORT_REGULAR ) );

// Make a JSON string from the array.
$result = json_encode( $array );

修改: 根据您对问题的 不要将$result分配给var_dump.将$result=var_dump( array_unique( $res, SORT_REGULAR ) );替换为$result=array_unique( $res, SORT_REGULAR );

Based on your edit in your question: Don't assign $result to a var_dump. Replace $result=var_dump( array_unique( $res, SORT_REGULAR ) ); by $result=array_unique( $res, SORT_REGULAR );

这篇关于如何使用PHP删除JSON对象的重复数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆