如何使用PHP拒绝重复数据并对JSON类型对象值进行排序

时间:2016-01-29 06:06:43

标签: php json

我需要一个帮助。我需要拒绝重复数据并使用PHP对json对象中存在的值进行排序。我正在解释下面的代码。

$res[]=array('member_name'=>$member,'no_of_members'=>$rowno['cnt'],'member_type'=>$countmemb);

$res的输出如下:

[
  {member_name:"Medilink member",member_type:"1",no_of_members:"383"},
  {member_name:"Medilink member",member_type:"1",no_of_members:"383"},
  {member_name:"Medilink member",member_type:"1",no_of_members:"383"},
  {member_name:"Non-Medilink Member",member_type:"2",no_of_members:"24"},
  {member_name:"Non-Medilink Member",member_type:"2",no_of_members:"24"}

]

我需要拒绝上面的重复行,结果值格式应如下所示。

$res=[
    {member_name:"Medilink member",member_type:"1",no_of_members:"383"},
    {member_name:"Non-Medilink Member",member_type:"2",no_of_members:"24"}
]

我需要上面给出的结果。请帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

您需要首先从多维数组中删除重复记录,然后使用json_encode以json格式获取结果

<?
// your array
$res[]=array('member_name'=>'Medilink member','no_of_members'=>1,'member_type'=>383);
$res[]=array('member_name'=>'Medilink member','no_of_members'=>1,'member_type'=>383);
$res[]=array('member_name'=>'Medilink member','no_of_members'=>1,'member_type'=>383);
$res[]=array('member_name'=>'Non-Medilink member','no_of_members'=>2,'member_type'=>24);
$res[]=array('member_name'=>'Non-Medilink member','no_of_members'=>2,'member_type'=>24);

// remove duplicates by using array_map and array_unique for multidimensional array
$duplicateRemoved = array_map("unserialize", array_unique(array_map("serialize", $res)));

// rearrange the array
$rearrangeArray = array_values($duplicateRemoved);

// encode the unique array into json format    
$encodedData = json_encode($rearrangeArray);

// print result    
echo $encodedData;    
?>

答案 1 :(得分:0)

&#13;
&#13;
// your array
$res[]=array('member_name'=>'Medilink member','no_of_members'=>1,'member_type'=>383);
$res[]=array('member_name'=>'Medilink member','no_of_members'=>1,'member_type'=>383);
$res[]=array('member_name'=>'Medilink member','no_of_members'=>1,'member_type'=>383);
$res[]=array('member_name'=>'Non-Medilink member','no_of_members'=>2,'member_type'=>24);
$res[]=array('member_name'=>'Non-Medilink member','no_of_members'=>2,'member_type'=>24);
$res = to_array_unique($res);
var_dump($res);exit;

function to_array_unique( $array ){
	$tmp_array = array();
	foreach( $array as $k => $v ){
		$tmp_array[] = json_encode($v);
	}
	$tmp_array = array_unique($tmp_array);

	$new_array = array();
	foreach ($tmp_array as $k2 => $v2) {
		$new_array[] = json_decode($v2);
	}
	return json_encode( $new_array );
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

结帐array_unique。这个内置函数会抛出所有重复的条目。

我将每一行转换为字符串,例如:https://3v4l.org/LjBZS