如何使用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_encode
it 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 );