如何从PHP中删除数组中的重复值?

时间:2015-07-14 09:26:03

标签: php

array=[{"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

{"poi":"ytr","wert":"yui","iuyy":"yes"},

{"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

{"poi":"ytr","wert":"yui","iuyy":"yes"},

{"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

{"poi":"ytr","wert":"yui","iuyy":"yes"},

{"abc":"qwe","sdsd":"ewewe","fff":"gggg"}]

输出将是:

array=[{"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

{"poi":"ytr","wert":"yui","iuyy":"yes"}]

请帮我解决这个问题 如果我正在尝试

此代码

    <?php

    $array=[{"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

    {"poi":"ytr","wert":"yui","iuyy":"yes"},

    {"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

    {"poi":"ytr","wert":"yui","iuyy":"yes"},

    {"abc":"qwe","sdsd":"ewewe","fff":"gggg"},

    {"poi":"ytr","wert":"yui","iuyy":"yes"},

    {"abc":"qwe","sdsd":"ewewe","fff":"gggg"}];

    $array = array_unique($array);

    echo $array;

    ?>

然后我得到运行时错误;在初始化时请帮助我从一个非常大的现有函数中获取这些数据。

3 个答案:

答案 0 :(得分:0)

试试这个..

array_unique()首先对作为字符串处理的值进行排序,然后保留每个值遇到的第一个键,并忽略所有后续键。这并不意味着将保留未排序数组中第一个相关值的键。

$getarray=json_decode(yourarray,true);

$array=array_unique($getarray);

http://php.net/manual/en/function.array-unique.php

答案 1 :(得分:0)

你可以使用array_unique函数,它接受一个数组并返回另一个没有重复的数组。

以下是一个例子:

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

答案 2 :(得分:0)

Your array initialization is wrong, Try this :

    <?php

$array=[["abc"=>"qwe","sdsd"=>"ewewe","fff"=>"gggg"],

    ["poi"=>"ytr","wert"=>"yui","iuyy"=>"yes"],

    ["abc"=>"qwe","sdsd"=>"ewewe","fff"=>"gggg"],

    ["poi"=>"ytr","wert"=>"yui","iuyy"=>"yes"],

    ["abc"=>"qwe","sdsd"=>"ewewe","fff"=>"gggg"],

    ["poi"=>"ytr","wert"=>"yui","iuyy"=>"yes"],

    ["abc"=>"qwe","sdsd"=>"ewewe","fff"=>"gggg"]

];
$unique=array(); 
$sorted_unique=array(); 
    for($n=0;$n<count($array);$n++) 
    { 
        $unique[]=serialize($array[$n]); 
    } 
    $array1=array_unique($unique); 
    for($n=0;$n<count($array1);$n++) 
    { 

            $sorted_unique[]=unserialize($array1[$n]); 

    } 
var_dump($sorted_unique);

?>